Skip to main content

kcode_session_history/
lib.rs

1//! Session lifecycle and local Session History.
2//!
3//! In-progress transcript entries live in `kcode-session-log`. Typed lifecycle,
4//! command, and stop records live in a separate `.session-control` journal.
5//! Successfully committed sessions leave a synchronized local receipt for
6//! their immutable Kweb object.
7
8/// Provider-independent Chatend state and durable session API.
9///
10/// This re-export preserves the original `kcode_session_history::chatend`
11/// boundary while `kcode-chatend` owns its cohesive implementation.
12pub mod chatend {
13    pub use kcode_chatend::{
14        BoxContent, BoxId, BoxOwner, BoxRepresentation, BoxState, CacheExpectation,
15        CanonicalRevision, Chatend, ContextProjection, ESTIMATED_BYTES_PER_TOKEN, Event, EventId,
16        EventKind, FORMAT_VERSION, MAX_OBJECT_BYTES, ObjectLocation, ObjectMetadata, PendingId,
17        PendingKind, PreparedProviderProjection, PreparedProviderResume, ProjectionItem,
18        ProviderContext, ProviderCostEstimate, ProviderCostEstimator, ProviderCostSummary,
19        ProviderMetering, ProviderTokenUsage, ProviderToolDefinition, Representation, Session,
20        SessionKind, SessionMetadata, SessionStatus, ToolSlot, ToolSlotInput, ToolState,
21        Transition, estimate_tokens,
22    };
23}
24pub use chatend::Session;
25pub use kcode_session_control_state::{SessionCommand, SessionRecord, SessionStopRequest};
26
27use std::{
28    collections::{BTreeMap, HashMap, HashSet},
29    fs::{File, OpenOptions},
30    io::{BufRead, BufReader, Write},
31    path::{Path as FilePath, PathBuf},
32    sync::{
33        Arc, Mutex, Weak,
34        atomic::{AtomicBool, Ordering},
35    },
36};
37
38use anyhow::{Context as _, ensure};
39use chrono::{DateTime, Utc};
40use kcode_chatend::SessionHistoryIntegration;
41use kcode_session_control_state::{ControlProjection, ControlUpdate, OpenMode, SessionControl};
42use kcode_session_log::{EventPosition, Role, Session as DurableSession, SessionLog, SessionStore};
43use serde::{Deserialize, Serialize};
44use serde_json::{Value, json};
45use tokio::sync::Notify;
46use uuid::Uuid;
47
48const RETAINED_INGRESS_FAILURES: usize = 5;
49
50struct SessionJournal {
51    log: DurableSession,
52    control: SessionControl,
53}
54
55impl SessionJournal {
56    fn create(directory: &FilePath, id: &str, created_at: &str) -> anyhow::Result<Self> {
57        let log = SessionStore::new(directory).create_session(id, created_at)?;
58        let control = SessionControl::open(directory, id, OpenMode::CreateNew)?
59            .context("created session-control journal was unexpectedly absent")?;
60        Ok(Self { log, control })
61    }
62
63    fn open(path: impl AsRef<FilePath>) -> anyhow::Result<Self> {
64        let path = path.as_ref();
65        ensure!(
66            path.extension().and_then(|value| value.to_str()) == Some("session-log"),
67            "{} is not a session-log path",
68            path.display()
69        );
70        let directory = path.parent().unwrap_or_else(|| FilePath::new("."));
71        let id = path
72            .file_stem()
73            .and_then(|value| value.to_str())
74            .context("session-log filename is not valid UTF-8")?;
75        let log = SessionStore::new(directory).open_session(id)?;
76        let control = SessionControl::open(directory, id, OpenMode::OpenOrCreate)?
77            .context("opened session-control journal was unexpectedly absent")?;
78        Ok(Self { log, control })
79    }
80
81    #[cfg(test)]
82    fn open_existing(path: impl AsRef<FilePath>) -> anyhow::Result<Option<Self>> {
83        let path = path.as_ref();
84        let Some(control) = open_listed_control(path)? else {
85            return Ok(None);
86        };
87        if control.projection().lifecycle.is_none() {
88            return Ok(None);
89        }
90        let (directory, id) = listed_session_parts(path)?;
91        let log = match SessionStore::new(directory).open_session(id) {
92            Ok(log) => log,
93            Err(_) if !path.exists() => return Ok(None),
94            Err(error) => return Err(error),
95        };
96        Ok(Some(Self { log, control }))
97    }
98
99    fn list(&self) -> SessionLog {
100        self.log.list()
101    }
102
103    fn projection(&self) -> ControlProjection {
104        self.control.projection()
105    }
106
107    fn append_control(&mut self, update: ControlUpdate) -> anyhow::Result<ControlUpdate> {
108        self.control.append(now(), update)
109    }
110
111    fn stage_object(
112        &mut self,
113        media_type: String,
114        file_name: Option<String>,
115        bytes: &[u8],
116    ) -> anyhow::Result<String> {
117        let file_name = file_name.unwrap_or_else(|| "uploaded-object".into());
118        let position =
119            self.log
120                .add_pending_object(file_name.clone(), file_name, media_type, bytes)?;
121        Ok(format!("pending:{}", position.index() + 1))
122    }
123}
124
125#[derive(Clone, Debug)]
126pub struct Config {
127    pub directory: PathBuf,
128    pub completed_list: PathBuf,
129    pub provider_cost_compatibility: Option<ProviderCostCompatibility>,
130}
131
132#[derive(Clone, Copy)]
133pub struct ProviderCostCompatibility {
134    pub session_model: fn(&Value) -> Option<String>,
135    pub estimator: chatend::ProviderCostEstimator,
136}
137
138impl std::fmt::Debug for ProviderCostCompatibility {
139    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        formatter
141            .debug_struct("ProviderCostCompatibility")
142            .finish_non_exhaustive()
143    }
144}
145
146#[derive(Clone, Debug)]
147pub struct NewSession {
148    pub kind: chatend::SessionKind,
149    pub created_at: String,
150    pub effective_context_tokens: u64,
151    pub channel: Value,
152}
153
154#[derive(Clone)]
155struct AppState {
156    config: Config,
157    catalog_mutation: Arc<Mutex<()>>,
158    session_mutations: Arc<Mutex<HashMap<String, Weak<Mutex<()>>>>>,
159    stop_listeners: Arc<Mutex<HashMap<String, Weak<StopSignal>>>>,
160}
161
162#[derive(Clone)]
163pub struct SessionHistory {
164    state: AppState,
165}
166
167struct StopSignal {
168    requested: AtomicBool,
169    notification: Notify,
170}
171
172#[derive(Clone)]
173pub struct StopListener {
174    signal: Arc<StopSignal>,
175}
176
177impl StopListener {
178    pub async fn requested(&self) {
179        loop {
180            let notified = self.signal.notification.notified();
181            tokio::pin!(notified);
182            notified.as_mut().enable();
183            if self.signal.requested.load(Ordering::Acquire) {
184                return;
185            }
186            notified.await;
187        }
188    }
189}
190
191#[derive(Debug)]
192pub struct Error {
193    pub kind: ErrorKind,
194    pub message: String,
195}
196
197#[derive(Clone, Copy, Debug, Eq, PartialEq)]
198pub enum ErrorKind {
199    InvalidInput,
200    NotFound,
201    Conflict,
202    Storage,
203}
204
205impl ErrorKind {
206    pub fn code(self) -> &'static str {
207        match self {
208            Self::InvalidInput => "invalid_request",
209            Self::NotFound => "not_found",
210            Self::Conflict => "state_conflict",
211            Self::Storage => "internal_error",
212        }
213    }
214}
215
216impl std::fmt::Display for Error {
217    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        formatter.write_str(&self.message)
219    }
220}
221
222impl std::error::Error for Error {}
223
224impl From<ApiError> for Error {
225    fn from(error: ApiError) -> Self {
226        Self {
227            kind: error.kind,
228            message: error.message,
229        }
230    }
231}
232
233#[derive(Debug)]
234struct ApiError {
235    kind: ErrorKind,
236    message: String,
237}
238
239impl ApiError {
240    fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
241        Self {
242            kind,
243            message: message.into(),
244        }
245    }
246
247    fn bad(message: impl Into<String>) -> Self {
248        Self::new(ErrorKind::InvalidInput, message)
249    }
250
251    fn not_found() -> Self {
252        Self::new(ErrorKind::NotFound, "Session not found.")
253    }
254
255    fn conflict(message: impl Into<String>) -> Self {
256        Self::new(ErrorKind::Conflict, message)
257    }
258
259    fn internal(error: impl std::fmt::Display) -> Self {
260        tracing::warn!(error=%format!("{error:#}"), "Session History request failed");
261        Self::new(
262            ErrorKind::Storage,
263            "An unexpected Session History storage error occurred.",
264        )
265    }
266}
267
268#[derive(Clone, Debug, Deserialize, Serialize)]
269pub struct RegisterSession {
270    pub id: String,
271    pub started_at: String,
272    pub state: Value,
273}
274
275#[derive(Clone, Debug, Deserialize, Serialize)]
276pub struct StartSession {
277    pub idempotency_id: String,
278    pub started_at: String,
279    pub session_type: String,
280    #[serde(default)]
281    pub duration_minutes: Option<f64>,
282    #[serde(default)]
283    pub custom_prompt: Option<String>,
284}
285
286#[derive(Clone, Debug, Deserialize, Serialize)]
287pub struct NewIngressSession {
288    pub idempotency_id: String,
289    pub started_at: String,
290    pub source_session_type: String,
291    pub kind: chatend::SessionKind,
292    pub effective_context_tokens: u64,
293    pub text: String,
294    #[serde(default)]
295    pub metadata: Value,
296}
297
298#[derive(Clone, Debug, Deserialize, Serialize)]
299pub struct NewCommand {
300    pub idempotency_id: String,
301    pub kind: String,
302    #[serde(default = "empty_object")]
303    pub payload: Value,
304}
305
306fn empty_object() -> Value {
307    json!({})
308}
309
310#[derive(Clone, Debug, Deserialize, Serialize)]
311pub struct CommandOutcome {
312    #[serde(default = "empty_object")]
313    pub outcome: Value,
314}
315
316#[derive(Clone, Debug, Deserialize, Serialize)]
317pub struct NewStopRequest {
318    pub idempotency_id: String,
319    pub scope: String,
320}
321
322#[derive(Clone, Debug, Deserialize, Serialize)]
323pub struct NewCurrentWorkStop {
324    pub idempotency_id: String,
325}
326
327#[derive(Clone, Debug, Deserialize, Serialize)]
328pub struct StopOutcome {
329    #[serde(default = "empty_object")]
330    pub outcome: Value,
331}
332
333#[derive(Clone, Debug, Deserialize, Serialize)]
334pub struct Checkpoint {
335    pub expected_version: i64,
336    pub state: Value,
337    #[serde(default)]
338    pub user_activity: bool,
339}
340
341#[derive(Clone, Debug, Deserialize, Serialize)]
342pub struct ExpectedVersion {
343    pub expected_version: i64,
344}
345
346#[derive(Clone, Debug, Deserialize, Serialize)]
347pub struct RetryIngress {
348    pub expected_version: i64,
349    pub state: Value,
350}
351
352#[derive(Clone, Debug, Deserialize, Serialize)]
353pub struct StartIngress {
354    pub expected_version: i64,
355    pub provenance_id: String,
356}
357
358#[derive(Clone, Debug, Deserialize, Serialize)]
359pub struct IngressFailure {
360    pub expected_version: i64,
361    pub stage: String,
362    #[serde(default)]
363    pub code: Option<String>,
364    pub message: String,
365    #[serde(default)]
366    pub rounds_used: Option<u64>,
367    #[serde(default)]
368    pub context_tokens: Option<u64>,
369    #[serde(default)]
370    pub context_window_tokens: Option<u64>,
371}
372
373#[derive(Clone, Debug, Deserialize, Serialize)]
374pub struct RecordCompletion {
375    pub session_object_id: String,
376    #[serde(default)]
377    pub commit_receipt: Option<CompletionReceipt>,
378    #[serde(default)]
379    pub session_id: Option<String>,
380    #[serde(default)]
381    pub session_type: Option<String>,
382    #[serde(default)]
383    pub created_at: Option<String>,
384}
385
386#[derive(Clone, Debug, Deserialize, Serialize)]
387#[serde(rename_all = "camelCase")]
388pub struct CompletionReceipt {
389    #[serde(default)]
390    pub transaction_id: Option<String>,
391    pub session_object_id: String,
392    #[serde(default)]
393    pub session_id: Option<String>,
394    #[serde(default)]
395    pub session_type: Option<String>,
396    #[serde(default)]
397    pub created_at: Option<String>,
398    #[serde(default)]
399    pub committed_at: Option<String>,
400    #[serde(default)]
401    pub ingress_source: Option<Value>,
402    #[serde(default)]
403    pub node_ids: BTreeMap<String, String>,
404    #[serde(default)]
405    pub object_ids: BTreeMap<String, String>,
406}
407
408#[derive(Clone, Debug, Eq, PartialEq)]
409pub struct Created<T> {
410    pub value: T,
411    pub created: bool,
412}
413
414#[derive(Clone, Debug)]
415pub struct NewObject {
416    pub file_name: Option<String>,
417    pub media_type: String,
418    pub bytes: Vec<u8>,
419}
420
421#[derive(Clone, Debug)]
422pub struct StoredObject {
423    pub file_name: String,
424    pub media_type: String,
425    pub bytes: Vec<u8>,
426}
427
428impl SessionHistory {
429    pub fn open(config: Config) -> anyhow::Result<Self> {
430        create_private_directory(&config.directory)?;
431        SessionControl::compact_directory(&config.directory)?;
432        if let Some(parent) = config
433            .completed_list
434            .parent()
435            .filter(|path| !path.as_os_str().is_empty())
436        {
437            create_private_directory(parent)?;
438        }
439        if !config.completed_list.exists() {
440            let file = OpenOptions::new()
441                .create_new(true)
442                .write(true)
443                .open(&config.completed_list)
444                .with_context(|| format!("creating {}", config.completed_list.display()))?;
445            file.sync_all()?;
446            sync_directory(
447                config
448                    .completed_list
449                    .parent()
450                    .filter(|path| !path.as_os_str().is_empty())
451                    .unwrap_or_else(|| FilePath::new(".")),
452            )?;
453        }
454        Ok(Self {
455            state: AppState {
456                config,
457                catalog_mutation: Arc::new(Mutex::new(())),
458                session_mutations: Arc::new(Mutex::new(HashMap::new())),
459                stop_listeners: Arc::new(Mutex::new(HashMap::new())),
460            },
461        })
462    }
463
464    pub fn health(&self) -> Result<(), Error> {
465        read_completed_ids(&self.state.config.completed_list).map_err(ApiError::internal)?;
466        Ok(())
467    }
468
469    pub fn create_session(&self, input: NewSession) -> anyhow::Result<Session> {
470        let metadata = chatend::SessionMetadata {
471            session_id: Uuid::new_v4().to_string(),
472            kind: input.kind,
473            created_at: input.created_at,
474            effective_context_tokens: input.effective_context_tokens,
475            channel: input.channel,
476        };
477        SessionHistoryIntegration::create_session(
478            self.state
479                .config
480                .directory
481                .join(format!("{}.session-log", metadata.session_id)),
482            metadata,
483        )
484    }
485
486    pub fn open_session(&self, metadata: chatend::SessionMetadata) -> anyhow::Result<Session> {
487        self.open_session_with_provider_model(metadata, None)
488    }
489
490    pub fn open_session_with_provider_model(
491        &self,
492        metadata: chatend::SessionMetadata,
493        provider_model: Option<&str>,
494    ) -> anyhow::Result<Session> {
495        validate_session_id(&metadata.session_id)
496            .map_err(|error| anyhow::anyhow!(error.message))?;
497        let path = self
498            .state
499            .config
500            .directory
501            .join(format!("{}.session-log", metadata.session_id));
502        match self.state.config.provider_cost_compatibility {
503            Some(compatibility) => SessionHistoryIntegration::open_session(
504                path,
505                metadata,
506                provider_model,
507                Some(compatibility.estimator),
508            ),
509            None => SessionHistoryIntegration::open_session(path, metadata, None, None),
510        }
511    }
512
513    pub fn legacy_provider_cost_summary_for_archive(
514        &self,
515        archive: &Value,
516        session_state: Option<&Value>,
517    ) -> anyhow::Result<Option<chatend::ProviderCostSummary>> {
518        let Some(compatibility) = self.state.config.provider_cost_compatibility else {
519            return Ok(None);
520        };
521        if is_metadata_free_session_log_archive(archive) {
522            return Ok(None);
523        }
524        let default_provider_model =
525            session_state.and_then(|state| (compatibility.session_model)(state));
526        SessionHistoryIntegration::legacy_provider_cost_summary_for_archive(
527            archive,
528            default_provider_model.as_deref(),
529            compatibility.estimator,
530        )
531        .map(Some)
532    }
533
534    pub async fn register(&self, input: RegisterSession) -> Result<SessionRecord, Error> {
535        create_session(self.state.clone(), input)
536            .await
537            .map_err(Into::into)
538    }
539
540    pub async fn start(&self, input: StartSession) -> Result<Created<SessionRecord>, Error> {
541        let (created, record) = start_managed_session(self.state.clone(), input).await?;
542        Ok(Created {
543            value: record,
544            created,
545        })
546    }
547
548    pub async fn enqueue_ingress(
549        &self,
550        input: NewIngressSession,
551    ) -> Result<Created<SessionRecord>, Error> {
552        let (created, record) = enqueue_ingress_session(self.state.clone(), input).await?;
553        Ok(Created {
554            value: record,
555            created,
556        })
557    }
558
559    pub async fn list(&self) -> Result<Vec<SessionRecord>, Error> {
560        list_session_summaries(self.state.clone())
561            .await
562            .map_err(Into::into)
563    }
564
565    pub async fn get(&self, id: &str) -> Result<SessionRecord, Error> {
566        get_session(self.state.clone(), id.to_owned())
567            .await
568            .map_err(Into::into)
569    }
570
571    pub async fn enqueue(
572        &self,
573        id: &str,
574        input: NewCommand,
575    ) -> Result<Created<SessionCommand>, Error> {
576        let (created, command) =
577            queue_session_command(self.state.clone(), id.to_owned(), input).await?;
578        Ok(Created {
579            value: command,
580            created,
581        })
582    }
583
584    pub async fn command_heads(&self) -> Result<Vec<SessionCommand>, Error> {
585        list_command_heads(self.state.clone())
586            .await
587            .map_err(Into::into)
588    }
589
590    pub async fn claim_command(&self, id: &str) -> Result<SessionCommand, Error> {
591        claim_command(self.state.clone(), id.to_owned())
592            .await
593            .map_err(Into::into)
594    }
595
596    pub async fn complete_command(
597        &self,
598        id: &str,
599        outcome: CommandOutcome,
600    ) -> Result<SessionCommand, Error> {
601        complete_command(self.state.clone(), id.to_owned(), outcome)
602            .await
603            .map_err(Into::into)
604    }
605
606    pub async fn request_stop(
607        &self,
608        id: &str,
609        input: NewStopRequest,
610    ) -> Result<Created<SessionStopRequest>, Error> {
611        let (created, request) = request_session_stop(
612            self.state.clone(),
613            id.to_owned(),
614            input.idempotency_id,
615            Some(input.scope),
616        )
617        .await?;
618        signal_stop_listener(&self.state, id).map_err(Error::from)?;
619        Ok(Created {
620            value: request,
621            created,
622        })
623    }
624
625    pub async fn request_current_work_stop(
626        &self,
627        id: &str,
628        input: NewCurrentWorkStop,
629    ) -> Result<Created<SessionStopRequest>, Error> {
630        let (created, request) = request_session_stop(
631            self.state.clone(),
632            id.to_owned(),
633            input.idempotency_id,
634            None,
635        )
636        .await?;
637        signal_stop_listener(&self.state, id).map_err(Error::from)?;
638        Ok(Created {
639            value: request,
640            created,
641        })
642    }
643
644    pub fn listen_for_stop(&self, id: &str) -> Result<StopListener, Error> {
645        listen_for_stop(&self.state, id).map_err(Into::into)
646    }
647
648    pub async fn stop_heads(&self) -> Result<Vec<SessionStopRequest>, Error> {
649        list_stop_heads(self.state.clone())
650            .await
651            .map_err(Into::into)
652    }
653
654    pub async fn complete_stop(
655        &self,
656        id: &str,
657        outcome: StopOutcome,
658    ) -> Result<SessionStopRequest, Error> {
659        complete_stop_request(self.state.clone(), id.to_owned(), outcome)
660            .await
661            .map_err(Into::into)
662    }
663
664    pub async fn stage_object(&self, id: &str, object: NewObject) -> Result<String, Error> {
665        stage_session_object(&self.state, id, object).map_err(Into::into)
666    }
667
668    pub fn object(&self, id: &str, pending_id: &str) -> Result<StoredObject, Error> {
669        get_session_object(&self.state, id, pending_id).map_err(Into::into)
670    }
671
672    pub async fn checkpoint(&self, id: &str, input: Checkpoint) -> Result<SessionRecord, Error> {
673        checkpoint(
674            self.state.clone(),
675            id,
676            input.expected_version,
677            input.state,
678            input.user_activity,
679        )
680        .await
681        .map_err(Into::into)
682    }
683
684    pub async fn request_ingress(
685        &self,
686        id: &str,
687        input: Checkpoint,
688    ) -> Result<SessionRecord, Error> {
689        transition_with_checkpoint(self.state.clone(), id, input, "ingress_pending")
690            .await
691            .map_err(Into::into)
692    }
693
694    pub async fn start_ingress(
695        &self,
696        id: &str,
697        input: StartIngress,
698    ) -> Result<SessionRecord, Error> {
699        transition(
700            self.state.clone(),
701            id,
702            input.expected_version,
703            "ingress_in_progress",
704            Some(input.provenance_id),
705        )
706        .await
707        .map_err(Into::into)
708    }
709
710    pub async fn complete_ingress(
711        &self,
712        id: &str,
713        input: ExpectedVersion,
714    ) -> Result<SessionRecord, Error> {
715        let current = fetch_active(&self.state, id)?;
716        complete_session(
717            self.state.clone(),
718            id,
719            input.expected_version,
720            current.state,
721        )
722        .await
723        .map_err(Into::into)
724    }
725
726    pub async fn fail_ingress(
727        &self,
728        id: &str,
729        input: IngressFailure,
730    ) -> Result<SessionRecord, Error> {
731        record_ingress_failure(self.state.clone(), id, input)
732            .await
733            .map_err(Into::into)
734    }
735
736    pub async fn retry_ingress(
737        &self,
738        id: &str,
739        input: RetryIngress,
740    ) -> Result<SessionRecord, Error> {
741        retry_ingress(self.state.clone(), id.to_owned(), input)
742            .await
743            .map_err(Into::into)
744    }
745
746    pub async fn release_interrupted_ingress(&self) -> Result<Vec<String>, Error> {
747        release_ingress_repairs(self.state.clone())
748            .await
749            .map_err(Into::into)
750    }
751
752    pub async fn complete(&self, id: &str, input: Checkpoint) -> Result<SessionRecord, Error> {
753        complete_session(self.state.clone(), id, input.expected_version, input.state)
754            .await
755            .map_err(Into::into)
756    }
757
758    pub async fn record_completion(&self, input: RecordCompletion) -> Result<(), Error> {
759        record_completed_session(self.state.clone(), input).await?;
760        Ok(())
761    }
762}
763
764fn is_metadata_free_session_log_archive(archive: &Value) -> bool {
765    if archive.get("metadata").is_some() {
766        return false;
767    }
768    let Some(header) = archive.get("header") else {
769        return false;
770    };
771    if header.get("formatVersion").and_then(Value::as_str)
772        != Some(kcode_session_log::FORMAT_VERSION)
773        || !header
774            .get("sessionId")
775            .and_then(Value::as_str)
776            .is_some_and(|value| !value.trim().is_empty())
777        || !header
778            .get("createdAt")
779            .and_then(Value::as_str)
780            .is_some_and(|value| !value.trim().is_empty())
781    {
782        return false;
783    }
784    archive
785        .get("events")
786        .and_then(Value::as_array)
787        .is_some_and(|events| {
788            events.iter().all(|event| {
789                event.get("text").and_then(Value::as_str).is_some()
790                    && event
791                        .get("role")
792                        .and_then(Value::as_str)
793                        .is_some_and(|role| {
794                            matches!(
795                                role,
796                                "system-message"
797                                    | "system-error"
798                                    | "user-message"
799                                    | "kennedy-message"
800                                    | "kennedy-tool-call"
801                                    | "tool-result"
802                                    | "tool-error"
803                                    | "object"
804                                    | "pending-object"
805                            )
806                        })
807            })
808        })
809}
810
811async fn record_completed_session(
812    state: AppState,
813    input: RecordCompletion,
814) -> Result<Value, ApiError> {
815    let session_guard = input
816        .session_id
817        .as_deref()
818        .map(|id| session_mutation(&state, id))
819        .transpose()?;
820    let _session_guard = session_guard
821        .as_ref()
822        .map(|guard| guard.lock().map_err(ApiError::internal))
823        .transpose()?;
824    let _catalog_guard = state.catalog_mutation.lock().map_err(ApiError::internal)?;
825    let mut receipt = input.commit_receipt.unwrap_or(CompletionReceipt {
826        transaction_id: None,
827        session_object_id: input.session_object_id.clone(),
828        session_id: None,
829        session_type: None,
830        created_at: None,
831        committed_at: None,
832        ingress_source: None,
833        node_ids: BTreeMap::new(),
834        object_ids: BTreeMap::new(),
835    });
836    if receipt.session_object_id != input.session_object_id {
837        return Err(ApiError::conflict(
838            "completion receipt and requested session object differ",
839        ));
840    }
841    receipt.session_id = receipt.session_id.or(input.session_id.clone());
842    receipt.session_type = receipt.session_type.or(input.session_type);
843    receipt.created_at = receipt.created_at.or(input.created_at);
844    receipt.committed_at.get_or_insert_with(now);
845    append_completion_receipt(&state.config.completed_list, &receipt)
846        .map_err(ApiError::internal)?;
847    if let Some(id) = input.session_id {
848        validate_session_id(&id)?;
849        let path = state.config.directory.join(format!("{id}.session-log"));
850        if path.exists() {
851            let SessionJournal { log, control } =
852                SessionJournal::open(&path).map_err(ApiError::internal)?;
853            log.delete_committed().map_err(ApiError::internal)?;
854            control.delete().map_err(ApiError::internal)?;
855        }
856    }
857    Ok(json!({
858        "sessionObjectId":input.session_object_id,
859        "recorded":true
860    }))
861}
862
863async fn create_session(
864    state: AppState,
865    input: RegisterSession,
866) -> Result<SessionRecord, ApiError> {
867    validate_started_at(&input.started_at)?;
868    validate_session_id(&input.id)?;
869    let path = state
870        .config
871        .directory
872        .join(format!("{}.session-log", input.id));
873    let journal = SessionJournal::open(&path).map_err(ApiError::internal)?;
874    let id = journal.list().header.session_id;
875    if id != input.id {
876        return Err(ApiError::bad(
877            "registered session ID does not match its durable session log",
878        ));
879    }
880    drop(journal);
881    let session_guard = session_mutation(&state, &id)?;
882    let _guard = session_guard.lock().map_err(ApiError::internal)?;
883    let mut journal = SessionJournal::open(&path).map_err(ApiError::internal)?;
884    if latest_lifecycle(&journal).is_some() {
885        return Err(ApiError::conflict("Session is already registered."));
886    }
887    let mut record = SessionRecord {
888        id,
889        phase: "active".into(),
890        started_at: input.started_at.clone(),
891        updated_at: input.started_at,
892        state: input.state,
893        provenance_id: None,
894        version: 1,
895        last_user_message_at: None,
896        ended_at: None,
897        ingress_failure_count: 0,
898        ingress_failures: json!([]),
899        ingress_next_attempt_at: None,
900        summary: false,
901    };
902    append_lifecycle(&mut journal, &mut record)?;
903    Ok(materialize(
904        record,
905        &journal,
906        state.config.provider_cost_compatibility,
907    ))
908}
909
910async fn start_managed_session(
911    state: AppState,
912    input: StartSession,
913) -> Result<(bool, SessionRecord), ApiError> {
914    validate_started_at(&input.started_at)?;
915    validate_idempotency(&input.idempotency_id)?;
916    let _catalog_guard = state.catalog_mutation.lock().map_err(ApiError::internal)?;
917    for path in journal_paths(&state.config.directory)? {
918        let journal = SessionJournal::open(&path).map_err(ApiError::internal)?;
919        if let Some(record) = latest_lifecycle(&journal)
920            && record
921                .state
922                .get("startIdempotencyId")
923                .and_then(Value::as_str)
924                == Some(&input.idempotency_id)
925        {
926            return Ok((
927                false,
928                materialize(record, &journal, state.config.provider_cost_compatibility),
929            ));
930        }
931    }
932    let id = Uuid::new_v4().to_string();
933    let mut journal = SessionJournal::create(&state.config.directory, &id, &input.started_at)
934        .map_err(ApiError::internal)?;
935    let mut session_state = json!({
936        "stateVersion":3,
937        "sessionId":id,
938        "sessionType":input.session_type,
939        "startedAt":input.started_at,
940        "startIdempotencyId":input.idempotency_id,
941        "orchestration":{"owner":"backend","status":"idle"},
942    });
943    if input.session_type == "free-time" {
944        session_state["selfTimeIntent"] = json!({
945            "requestedAt":input.started_at,
946            "durationMinutes":input.duration_minutes,
947            "customPrompt":input.custom_prompt.unwrap_or_default(),
948        });
949    }
950    let mut record = SessionRecord {
951        id,
952        phase: "active".into(),
953        started_at: input.started_at.clone(),
954        updated_at: input.started_at,
955        state: session_state,
956        provenance_id: None,
957        version: 1,
958        last_user_message_at: None,
959        ended_at: None,
960        ingress_failure_count: 0,
961        ingress_failures: json!([]),
962        ingress_next_attempt_at: None,
963        summary: false,
964    };
965    append_lifecycle(&mut journal, &mut record)?;
966    Ok((
967        true,
968        materialize(record, &journal, state.config.provider_cost_compatibility),
969    ))
970}
971
972async fn enqueue_ingress_session(
973    state: AppState,
974    input: NewIngressSession,
975) -> Result<(bool, SessionRecord), ApiError> {
976    validate_started_at(&input.started_at)?;
977    validate_idempotency(&input.idempotency_id)?;
978    if input.source_session_type.trim().is_empty() {
979        return Err(ApiError::bad("Source session type must not be empty."));
980    }
981    if input.text.trim().is_empty() {
982        return Err(ApiError::bad("Ingress source text must not be empty."));
983    }
984    let _catalog_guard = state.catalog_mutation.lock().map_err(ApiError::internal)?;
985    for path in journal_paths(&state.config.directory)? {
986        let journal = SessionJournal::open(&path).map_err(ApiError::internal)?;
987        if let Some(record) = latest_lifecycle(&journal)
988            && ingress_idempotency_id(record.state.get("ingressSource"))
989                == Some(input.idempotency_id.as_str())
990        {
991            return Ok((
992                false,
993                materialize(record, &journal, state.config.provider_cost_compatibility),
994            ));
995        }
996    }
997    for receipt in
998        read_completion_receipts(&state.config.completed_list).map_err(ApiError::internal)?
999    {
1000        if ingress_idempotency_id(receipt.ingress_source.as_ref())
1001            == Some(input.idempotency_id.as_str())
1002        {
1003            return Ok((false, completed_session_record(receipt, false)));
1004        }
1005    }
1006
1007    let id = Uuid::new_v4().to_string();
1008    let path = state.config.directory.join(format!("{id}.session-log"));
1009    let mut source = SessionHistoryIntegration::create_session(
1010        &path,
1011        chatend::SessionMetadata {
1012            session_id: id.clone(),
1013            kind: input.kind,
1014            created_at: input.started_at.clone(),
1015            effective_context_tokens: input.effective_context_tokens,
1016            channel: Value::Null,
1017        },
1018    )
1019    .map_err(ApiError::internal)?;
1020    source
1021        .create_box(
1022            input.started_at.clone(),
1023            "Ingress source",
1024            chatend::BoxOwner::User,
1025            chatend::BoxContent {
1026                text: input.text.trim().to_owned(),
1027                objects: Vec::new(),
1028                metadata: input.metadata.clone(),
1029            },
1030        )
1031        .map_err(ApiError::internal)?;
1032    let chatend_metadata = source.state().metadata.clone();
1033    drop(source);
1034
1035    let ingress_source = json!({
1036        "idempotencyId":input.idempotency_id,
1037        "metadata":input.metadata,
1038    });
1039    let mut journal = SessionJournal::open(&path).map_err(ApiError::internal)?;
1040    let mut record = SessionRecord {
1041        id: id.clone(),
1042        phase: "ingress_pending".into(),
1043        started_at: input.started_at.clone(),
1044        updated_at: input.started_at.clone(),
1045        state: json!({
1046            "stateVersion":3,
1047            "sessionId":id,
1048            "sessionType":input.source_session_type,
1049            "startedAt":input.started_at,
1050            "ingressSource":ingress_source,
1051            "chatendMetadata":chatend_metadata,
1052        }),
1053        provenance_id: None,
1054        version: 1,
1055        last_user_message_at: None,
1056        ended_at: None,
1057        ingress_failure_count: 0,
1058        ingress_failures: json!([]),
1059        ingress_next_attempt_at: None,
1060        summary: false,
1061    };
1062    append_lifecycle(&mut journal, &mut record)?;
1063    Ok((
1064        true,
1065        materialize(record, &journal, state.config.provider_cost_compatibility),
1066    ))
1067}
1068
1069fn ingress_idempotency_id(source: Option<&Value>) -> Option<&str> {
1070    source?.get("idempotencyId").and_then(Value::as_str)
1071}
1072
1073async fn list_session_summaries(state: AppState) -> Result<Vec<SessionRecord>, ApiError> {
1074    let mut sessions = Vec::new();
1075    for projection in open_listed_control_projections(journal_paths(&state.config.directory)?)? {
1076        if let Some(mut record) = projection.lifecycle {
1077            record.summary = true;
1078            record.state = summary_state(&record.state);
1079            sessions.push(record);
1080        }
1081    }
1082    let receipts =
1083        read_completion_receipts(&state.config.completed_list).map_err(ApiError::internal)?;
1084    let completed_session_ids = receipts
1085        .iter()
1086        .filter_map(|receipt| receipt.session_id.as_ref())
1087        .collect::<HashSet<_>>();
1088    sessions.retain(|session| !completed_session_ids.contains(&session.id));
1089    for receipt in receipts {
1090        sessions.push(completed_session_record(receipt, true));
1091    }
1092    sessions.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
1093    Ok(sessions)
1094}
1095
1096async fn get_session(state: AppState, id: String) -> Result<SessionRecord, ApiError> {
1097    if let Some(receipt) = read_completion_receipts(&state.config.completed_list)
1098        .map_err(ApiError::internal)?
1099        .into_iter()
1100        .find(|receipt| receipt.session_object_id == id)
1101    {
1102        return Ok(completed_session_record(receipt, false));
1103    }
1104    let journal = open_by_id(&state, &id)?;
1105    let record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1106    Ok(materialize(
1107        record,
1108        &journal,
1109        state.config.provider_cost_compatibility,
1110    ))
1111}
1112
1113fn completed_session_record(receipt: CompletionReceipt, summary: bool) -> SessionRecord {
1114    let object_id = receipt.session_object_id.clone();
1115    let started_at = receipt.created_at.clone().unwrap_or_default();
1116    let updated_at = receipt.committed_at.clone().unwrap_or_default();
1117    SessionRecord {
1118        id: object_id.clone(),
1119        phase: "complete".into(),
1120        started_at,
1121        updated_at,
1122        state: json!({
1123            "sessionObjectId":object_id,
1124            "sessionId":receipt.session_id.clone(),
1125            "sessionType":receipt.session_type.clone(),
1126            "ingressSource":receipt.ingress_source.clone(),
1127            "commitReceipt":receipt,
1128        }),
1129        provenance_id: None,
1130        version: 1,
1131        last_user_message_at: None,
1132        ended_at: None,
1133        ingress_failure_count: 0,
1134        ingress_failures: json!([]),
1135        ingress_next_attempt_at: None,
1136        summary,
1137    }
1138}
1139
1140fn get_session_object(
1141    state: &AppState,
1142    id: &str,
1143    pending_id: &str,
1144) -> Result<StoredObject, ApiError> {
1145    let number = pending_id
1146        .strip_prefix("pending:")
1147        .and_then(|value| value.parse::<u64>().ok())
1148        .filter(|value| *value > 0)
1149        .ok_or_else(|| ApiError::bad("Object ID must have the form pending:N."))?;
1150    let journal = open_by_id(state, id)?;
1151    let object = journal
1152        .log
1153        .read_pending_object(EventPosition(number - 1))
1154        .map_err(|error| {
1155            tracing::warn!(session_id=id, pending_id, %error, "pending session object is unavailable");
1156            ApiError::not_found()
1157        })?;
1158    let media_type = if object.media_type.trim().is_empty()
1159        || object
1160            .media_type
1161            .chars()
1162            .any(|character| character.is_control() || character.is_whitespace())
1163        || !object.media_type.contains('/')
1164    {
1165        "application/octet-stream"
1166    } else {
1167        &object.media_type
1168    };
1169    let mut file_name = object
1170        .file_name
1171        .chars()
1172        .map(|character| {
1173            if character.is_ascii_graphic() && !matches!(character, '"' | '\\' | '/' | ';') {
1174                character
1175            } else {
1176                '_'
1177            }
1178        })
1179        .take(255)
1180        .collect::<String>();
1181    if file_name.is_empty() {
1182        file_name = "uploaded-object".into();
1183    }
1184    Ok(StoredObject {
1185        file_name,
1186        media_type: media_type.to_owned(),
1187        bytes: object.bytes,
1188    })
1189}
1190
1191async fn queue_session_command(
1192    state: AppState,
1193    id: String,
1194    input: NewCommand,
1195) -> Result<(bool, SessionCommand), ApiError> {
1196    validate_idempotency(&input.idempotency_id)?;
1197    let session_guard = session_mutation(&state, &id)?;
1198    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1199    let mut journal = open_by_id(&state, &id)?;
1200    let record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1201    if record.phase != "active" {
1202        return Err(ApiError::conflict("Session is no longer active."));
1203    }
1204    let commands = commands(&journal);
1205    if let Some(command) = commands
1206        .values()
1207        .find(|command| command.idempotency_id == input.idempotency_id)
1208    {
1209        return Ok((false, command.clone()));
1210    }
1211    let command = SessionCommand {
1212        id: Uuid::new_v4().to_string(),
1213        conversation_id: id,
1214        sequence: commands
1215            .values()
1216            .map(|command| command.sequence)
1217            .max()
1218            .unwrap_or(0)
1219            + 1,
1220        kind: input.kind,
1221        payload: input.payload,
1222        status: "pending".into(),
1223        cancel_requested: false,
1224        outcome: None,
1225        created_at: now(),
1226        processing_started_at: None,
1227        completed_at: None,
1228        idempotency_id: input.idempotency_id,
1229    };
1230    append_command(&mut journal, &command)?;
1231    Ok((true, command))
1232}
1233
1234fn stage_session_object(state: &AppState, id: &str, object: NewObject) -> Result<String, ApiError> {
1235    let NewObject {
1236        file_name,
1237        media_type,
1238        bytes,
1239    } = object;
1240    let session_guard = session_mutation(state, id)?;
1241    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1242    let mut journal = open_by_id(state, id)?;
1243    let record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1244    if record.phase != "active" {
1245        return Err(ApiError::conflict(
1246            "Objects can only be supplied to an active session.",
1247        ));
1248    }
1249    if commands(&journal)
1250        .values()
1251        .any(|command| matches!(command.status.as_str(), "pending" | "processing"))
1252    {
1253        return Err(ApiError::conflict(
1254            "Objects cannot be supplied while the session is processing a command.",
1255        ));
1256    }
1257    journal
1258        .stage_object(media_type, file_name, &bytes)
1259        .map_err(|error| ApiError::bad(error.to_string()))
1260}
1261
1262async fn list_command_heads(state: AppState) -> Result<Vec<SessionCommand>, ApiError> {
1263    let mut heads = Vec::new();
1264    for projection in open_listed_control_projections(journal_paths(&state.config.directory)?)? {
1265        let mut active = projection
1266            .commands
1267            .into_values()
1268            .filter(|command| matches!(command.status.as_str(), "pending" | "processing"))
1269            .collect::<Vec<_>>();
1270        active.sort_by_key(|command| command.sequence);
1271        if let Some(head) = active.into_iter().next() {
1272            heads.push(head);
1273        }
1274    }
1275    heads.sort_by(|a, b| a.created_at.cmp(&b.created_at));
1276    Ok(heads)
1277}
1278
1279async fn claim_command(state: AppState, command_id: String) -> Result<SessionCommand, ApiError> {
1280    mutate_command(&state, &command_id, |command| {
1281        if command.status == "pending" {
1282            command.status = "processing".into();
1283            command.processing_started_at = Some(now());
1284        } else if command.status != "processing" {
1285            return Err(ApiError::conflict("Command is already complete."));
1286        }
1287        Ok(())
1288    })
1289}
1290
1291async fn complete_command(
1292    state: AppState,
1293    command_id: String,
1294    input: CommandOutcome,
1295) -> Result<SessionCommand, ApiError> {
1296    mutate_command(&state, &command_id, |command| {
1297        if command.status == "complete" {
1298            return Ok(());
1299        }
1300        if command.status != "processing" {
1301            return Err(ApiError::conflict("Command was not claimed."));
1302        }
1303        command.status = "complete".into();
1304        command.outcome = Some(input.outcome);
1305        command.completed_at = Some(now());
1306        Ok(())
1307    })
1308}
1309
1310async fn request_session_stop(
1311    state: AppState,
1312    id: String,
1313    idempotency_id: String,
1314    requested_scope: Option<String>,
1315) -> Result<(bool, SessionStopRequest), ApiError> {
1316    validate_idempotency(&idempotency_id)?;
1317    if requested_scope
1318        .as_deref()
1319        .is_some_and(|scope| !matches!(scope, "turn" | "session" | "self-time-run"))
1320    {
1321        return Err(ApiError::bad(
1322            "Stop scope must be turn, session, or self-time-run.",
1323        ));
1324    }
1325    let session_guard = session_mutation(&state, &id)?;
1326    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1327    let mut journal = open_by_id(&state, &id)?;
1328    let lifecycle = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1329    if !matches!(
1330        lifecycle.phase.as_str(),
1331        "active" | "ingress_pending" | "ingress_in_progress"
1332    ) {
1333        return Err(ApiError::conflict("Session has no work in progress."));
1334    }
1335    let existing = stop_requests(&journal);
1336    if let Some(request) = existing
1337        .values()
1338        .find(|request| request.idempotency_id == idempotency_id)
1339    {
1340        return Ok((false, request.clone()));
1341    }
1342    if let Some(request) = existing
1343        .values()
1344        .find(|request| request.status == "pending")
1345    {
1346        return Ok((false, request.clone()));
1347    }
1348    let scope = match requested_scope {
1349        Some(scope) => scope,
1350        None => current_work_stop_scope(&lifecycle)?.into(),
1351    };
1352    let request = SessionStopRequest {
1353        id: Uuid::new_v4().to_string(),
1354        session_id: id,
1355        scope,
1356        status: "pending".into(),
1357        outcome: None,
1358        requested_at: now(),
1359        completed_at: None,
1360        idempotency_id,
1361    };
1362    append_stop_request(&mut journal, &request)?;
1363
1364    if request.scope == "turn" {
1365        let mut active = commands(&journal)
1366            .into_values()
1367            .filter(|command| {
1368                matches!(command.status.as_str(), "pending" | "processing")
1369                    && matches!(command.kind.as_str(), "message" | "retry")
1370            })
1371            .collect::<Vec<_>>();
1372        active.sort_by_key(|command| command.sequence);
1373        if let Some(mut command) = active.into_iter().next() {
1374            command.cancel_requested = true;
1375            append_command(&mut journal, &command)?;
1376        }
1377    }
1378    Ok((true, request))
1379}
1380
1381fn current_work_stop_scope(record: &SessionRecord) -> Result<&'static str, ApiError> {
1382    if record.phase != "active" {
1383        return Ok("session");
1384    }
1385    let kind = record
1386        .state
1387        .get("chatendMetadata")
1388        .cloned()
1389        .and_then(|value| serde_json::from_value::<chatend::SessionMetadata>(value).ok())
1390        .map(|metadata| metadata.kind);
1391    match kind {
1392        Some(
1393            chatend::SessionKind::Conversation
1394            | chatend::SessionKind::Telegram
1395            | chatend::SessionKind::TelegramGroup,
1396        ) => Ok("turn"),
1397        Some(chatend::SessionKind::SelfTime) => Ok("self-time-run"),
1398        Some(_) => Ok("session"),
1399        None => match record.state.get("sessionType").and_then(Value::as_str) {
1400            Some("conversation" | "telegram" | "telegram-group") => Ok("turn"),
1401            Some("free-time") => Ok("self-time-run"),
1402            Some(_) => Ok("session"),
1403            None => Err(ApiError::conflict(
1404                "Session does not identify the work that should stop.",
1405            )),
1406        },
1407    }
1408}
1409
1410fn listen_for_stop(state: &AppState, id: &str) -> Result<StopListener, ApiError> {
1411    let session_guard = session_mutation(state, id)?;
1412    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1413    let journal = open_by_id(state, id)?;
1414    let signal = {
1415        let mut listeners = state.stop_listeners.lock().map_err(ApiError::internal)?;
1416        listeners.retain(|_, listener| listener.strong_count() > 0);
1417        if let Some(signal) = listeners.get(id).and_then(Weak::upgrade) {
1418            signal
1419        } else {
1420            let signal = Arc::new(StopSignal {
1421                requested: AtomicBool::new(false),
1422                notification: Notify::new(),
1423            });
1424            listeners.insert(id.to_owned(), Arc::downgrade(&signal));
1425            signal
1426        }
1427    };
1428    if stop_requests(&journal)
1429        .values()
1430        .any(|request| request.status == "pending")
1431    {
1432        signal_stop(&signal);
1433    }
1434    Ok(StopListener { signal })
1435}
1436
1437fn signal_stop_listener(state: &AppState, id: &str) -> Result<(), ApiError> {
1438    let signal = state
1439        .stop_listeners
1440        .lock()
1441        .map_err(ApiError::internal)?
1442        .get(id)
1443        .and_then(Weak::upgrade);
1444    if let Some(signal) = signal {
1445        signal_stop(&signal);
1446    }
1447    Ok(())
1448}
1449
1450fn signal_stop(signal: &StopSignal) {
1451    signal.requested.store(true, Ordering::Release);
1452    signal.notification.notify_waiters();
1453}
1454
1455async fn list_stop_heads(state: AppState) -> Result<Vec<SessionStopRequest>, ApiError> {
1456    let mut heads = Vec::new();
1457    for projection in open_listed_control_projections(journal_paths(&state.config.directory)?)? {
1458        if let Some(request) = projection
1459            .stop_requests
1460            .into_values()
1461            .find(|request| request.status == "pending")
1462        {
1463            heads.push(request);
1464        }
1465    }
1466    heads.sort_by(|left, right| left.requested_at.cmp(&right.requested_at));
1467    Ok(heads)
1468}
1469
1470async fn complete_stop_request(
1471    state: AppState,
1472    request_id: String,
1473    input: StopOutcome,
1474) -> Result<SessionStopRequest, ApiError> {
1475    mutate_stop_request(&state, &request_id, |request| {
1476        if request.status == "complete" {
1477            return Ok(());
1478        }
1479        request.status = "complete".into();
1480        request.outcome = Some(input.outcome);
1481        request.completed_at = Some(now());
1482        Ok(())
1483    })
1484}
1485
1486fn mutate_command(
1487    state: &AppState,
1488    command_id: &str,
1489    mutation: impl FnOnce(&mut SessionCommand) -> Result<(), ApiError>,
1490) -> Result<SessionCommand, ApiError> {
1491    let mut target = None;
1492    for path in journal_paths(&state.config.directory)? {
1493        let journal = SessionJournal::open(&path).map_err(ApiError::internal)?;
1494        if let Some(command) = commands(&journal).remove(command_id) {
1495            target = Some((path, command.conversation_id));
1496            break;
1497        }
1498    }
1499    let (path, conversation_id) = target.ok_or_else(ApiError::not_found)?;
1500    let session_guard = session_mutation(state, &conversation_id)?;
1501    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1502    let mut journal = SessionJournal::open(path).map_err(ApiError::internal)?;
1503    let mut command = commands(&journal)
1504        .remove(command_id)
1505        .ok_or_else(ApiError::not_found)?;
1506    mutation(&mut command)?;
1507    append_command(&mut journal, &command)?;
1508    Ok(command)
1509}
1510
1511fn mutate_stop_request(
1512    state: &AppState,
1513    request_id: &str,
1514    mutation: impl FnOnce(&mut SessionStopRequest) -> Result<(), ApiError>,
1515) -> Result<SessionStopRequest, ApiError> {
1516    let mut target = None;
1517    for path in journal_paths(&state.config.directory)? {
1518        let journal = SessionJournal::open(&path).map_err(ApiError::internal)?;
1519        if let Some(request) = stop_requests(&journal).remove(request_id) {
1520            target = Some((path, request.session_id));
1521            break;
1522        }
1523    }
1524    let (path, session_id) = target.ok_or_else(ApiError::not_found)?;
1525    let session_guard = session_mutation(state, &session_id)?;
1526    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1527    let mut journal = SessionJournal::open(path).map_err(ApiError::internal)?;
1528    let mut request = stop_requests(&journal)
1529        .remove(request_id)
1530        .ok_or_else(ApiError::not_found)?;
1531    mutation(&mut request)?;
1532    append_stop_request(&mut journal, &request)?;
1533    Ok(request)
1534}
1535
1536async fn checkpoint(
1537    state: AppState,
1538    id: &str,
1539    expected_version: i64,
1540    new_state: Value,
1541    user_activity: bool,
1542) -> Result<SessionRecord, ApiError> {
1543    let session_guard = session_mutation(&state, id)?;
1544    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1545    let mut journal = open_by_id(&state, id)?;
1546    let mut record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1547    require_version(&record, expected_version)?;
1548    record.state = new_state;
1549    record.version += 1;
1550    record.updated_at = now();
1551    if user_activity {
1552        record.last_user_message_at = Some(record.updated_at.clone());
1553    }
1554    append_lifecycle(&mut journal, &mut record)?;
1555    Ok(materialize(
1556        record,
1557        &journal,
1558        state.config.provider_cost_compatibility,
1559    ))
1560}
1561
1562async fn transition_with_checkpoint(
1563    state: AppState,
1564    id: &str,
1565    input: Checkpoint,
1566    phase: &str,
1567) -> Result<SessionRecord, ApiError> {
1568    let session_guard = session_mutation(&state, id)?;
1569    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1570    let mut journal = open_by_id(&state, id)?;
1571    let mut record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1572    require_version(&record, input.expected_version)?;
1573    record.state = input.state;
1574    record.phase = phase.into();
1575    if phase == "ingress_pending" {
1576        record.ingress_next_attempt_at = None;
1577    }
1578    record.version += 1;
1579    record.updated_at = now();
1580    append_lifecycle(&mut journal, &mut record)?;
1581    Ok(materialize(
1582        record,
1583        &journal,
1584        state.config.provider_cost_compatibility,
1585    ))
1586}
1587
1588async fn transition(
1589    state: AppState,
1590    id: &str,
1591    expected_version: i64,
1592    phase: &str,
1593    provenance_id: Option<String>,
1594) -> Result<SessionRecord, ApiError> {
1595    let session_guard = session_mutation(&state, id)?;
1596    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1597    let mut journal = open_by_id(&state, id)?;
1598    let mut record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1599    require_version(&record, expected_version)?;
1600    record.phase = phase.into();
1601    record.provenance_id = provenance_id;
1602    if phase == "ingress_in_progress" {
1603        record.ingress_next_attempt_at = None;
1604    }
1605    record.version += 1;
1606    record.updated_at = now();
1607    append_lifecycle(&mut journal, &mut record)?;
1608    Ok(materialize(
1609        record,
1610        &journal,
1611        state.config.provider_cost_compatibility,
1612    ))
1613}
1614
1615async fn record_ingress_failure(
1616    state: AppState,
1617    id: &str,
1618    input: IngressFailure,
1619) -> Result<SessionRecord, ApiError> {
1620    let session_guard = session_mutation(&state, id)?;
1621    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1622    let mut journal = open_by_id(&state, id)?;
1623    let mut record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1624    require_version(&record, input.expected_version)?;
1625    if !matches!(
1626        record.phase.as_str(),
1627        "ingress_pending" | "ingress_in_progress"
1628    ) {
1629        return Err(ApiError::conflict(
1630            "Session History ingress is not in an active attempt.",
1631        ));
1632    }
1633    let attempt = record.ingress_failure_count.saturating_add(1);
1634    let mut failures = record
1635        .ingress_failures
1636        .as_array()
1637        .cloned()
1638        .unwrap_or_default();
1639    failures.push(json!({
1640        "attempt":attempt,
1641        "at":now(),
1642        "stage":input.stage,
1643        "code":input.code,
1644        "message":input.message,
1645        "roundsUsed":input.rounds_used,
1646        "contextTokens":input.context_tokens,
1647        "contextWindowTokens":input.context_window_tokens,
1648    }));
1649    if failures.len() > RETAINED_INGRESS_FAILURES {
1650        failures.drain(..failures.len() - RETAINED_INGRESS_FAILURES);
1651    }
1652    record.ingress_failures = Value::Array(failures);
1653    record.ingress_failure_count = attempt;
1654    record.phase = "ingress_failed".into();
1655    record.ingress_next_attempt_at = None;
1656    record.version += 1;
1657    record.updated_at = now();
1658    append_lifecycle(&mut journal, &mut record)?;
1659    tracing::error!(
1660        session_id = id,
1661        attempt,
1662        stage = %input.stage,
1663        code = input.code.as_deref().unwrap_or("ingress_error"),
1664        "Session History ingress stopped until manual retry"
1665    );
1666    Ok(materialize(
1667        record,
1668        &journal,
1669        state.config.provider_cost_compatibility,
1670    ))
1671}
1672
1673async fn retry_ingress(
1674    state: AppState,
1675    id: String,
1676    input: RetryIngress,
1677) -> Result<SessionRecord, ApiError> {
1678    let session_guard = session_mutation(&state, &id)?;
1679    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1680    let mut journal = open_by_id(&state, &id)?;
1681    let mut record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1682    require_version(&record, input.expected_version)?;
1683    if record.phase != "ingress_failed" {
1684        return Err(ApiError::conflict(
1685            "Session History ingress is not in the failed state.",
1686        ));
1687    }
1688    record.state = input.state;
1689    if let Some(state) = record.state.as_object_mut() {
1690        state.remove("historyIngress");
1691    }
1692    record.phase = "ingress_pending".into();
1693    record.ingress_failure_count = 0;
1694    record.ingress_next_attempt_at = None;
1695    record.version += 1;
1696    record.updated_at = now();
1697    append_lifecycle(&mut journal, &mut record)?;
1698    Ok(materialize(
1699        record,
1700        &journal,
1701        state.config.provider_cost_compatibility,
1702    ))
1703}
1704
1705async fn release_ingress_repairs(state: AppState) -> Result<Vec<String>, ApiError> {
1706    let mut released = Vec::new();
1707    for path in journal_paths(&state.config.directory)? {
1708        let Some(id) = path
1709            .file_stem()
1710            .and_then(|value| value.to_str())
1711            .map(str::to_owned)
1712        else {
1713            continue;
1714        };
1715        let session_guard = session_mutation(&state, &id)?;
1716        let _guard = session_guard.lock().map_err(ApiError::internal)?;
1717        let mut journal = open_by_id(&state, &id)?;
1718        let Some(mut record) = latest_lifecycle(&journal) else {
1719            continue;
1720        };
1721        if record.phase != "ingress_in_progress" {
1722            continue;
1723        }
1724        let attempt = record.ingress_failure_count.saturating_add(1);
1725        let failed_at = now();
1726        let mut failures = record
1727            .ingress_failures
1728            .as_array()
1729            .cloned()
1730            .unwrap_or_default();
1731        failures.push(json!({
1732            "attempt":attempt,
1733            "at":failed_at.clone(),
1734            "stage":"process_restart",
1735            "code":"ingress_interrupted",
1736            "message":"The ingress process stopped before the attempt completed.",
1737            "roundsUsed":Value::Null,
1738            "contextTokens":Value::Null,
1739            "contextWindowTokens":Value::Null,
1740        }));
1741        if failures.len() > RETAINED_INGRESS_FAILURES {
1742            failures.drain(..failures.len() - RETAINED_INGRESS_FAILURES);
1743        }
1744        record.ingress_failures = Value::Array(failures);
1745        record.ingress_failure_count = attempt;
1746        record.phase = "ingress_failed".into();
1747        record.ingress_next_attempt_at = None;
1748        record.version += 1;
1749        record.updated_at = failed_at;
1750        append_lifecycle(&mut journal, &mut record)?;
1751        released.push(id);
1752    }
1753    Ok(released)
1754}
1755
1756async fn complete_session(
1757    state: AppState,
1758    id: &str,
1759    expected_version: i64,
1760    new_state: Value,
1761) -> Result<SessionRecord, ApiError> {
1762    let session_guard = session_mutation(&state, id)?;
1763    let _guard = session_guard.lock().map_err(ApiError::internal)?;
1764    let journal = open_by_id(&state, id)?;
1765    let mut record = latest_lifecycle(&journal).ok_or_else(ApiError::not_found)?;
1766    require_version(&record, expected_version)?;
1767    let completion_state = new_state
1768        .get("historyIngress")
1769        .filter(|state| state.get("sessionObjectId").is_some_and(Value::is_string))
1770        .cloned()
1771        .unwrap_or_else(|| new_state.clone());
1772    record.state = new_state;
1773    record = projected_lifecycle(record);
1774    let object_id = completion_state
1775        .get("sessionObjectId")
1776        .and_then(Value::as_str)
1777        .ok_or_else(|| {
1778            ApiError::conflict("completed session has no permanent Kweb session object")
1779        })?
1780        .to_owned();
1781    let _catalog_guard = state.catalog_mutation.lock().map_err(ApiError::internal)?;
1782    let mut receipt = completion_state
1783        .get("commitReceipt")
1784        .filter(|receipt| !receipt.is_null())
1785        .cloned()
1786        .map(serde_json::from_value::<CompletionReceipt>)
1787        .transpose()
1788        .map_err(|error| ApiError::conflict(format!("invalid session commit receipt: {error}")))?
1789        .unwrap_or(CompletionReceipt {
1790            transaction_id: None,
1791            session_object_id: object_id.clone(),
1792            session_id: None,
1793            session_type: None,
1794            created_at: None,
1795            committed_at: None,
1796            ingress_source: None,
1797            node_ids: BTreeMap::new(),
1798            object_ids: BTreeMap::new(),
1799        });
1800    if receipt.session_object_id != object_id {
1801        return Err(ApiError::conflict(
1802            "session commit receipt names a different archive object",
1803        ));
1804    }
1805    let completed_at = now();
1806    receipt.session_id = Some(record.id.clone());
1807    receipt.session_type = record
1808        .state
1809        .get("sessionType")
1810        .and_then(Value::as_str)
1811        .map(str::to_owned);
1812    receipt.created_at = Some(record.started_at.clone());
1813    receipt.committed_at = Some(completed_at.clone());
1814    receipt.ingress_source = record.state.get("ingressSource").cloned();
1815    append_completion_receipt(&state.config.completed_list, &receipt)
1816        .map_err(ApiError::internal)?;
1817    record.phase = "complete".into();
1818    record.version += 1;
1819    record.updated_at = completed_at;
1820    record.ended_at = Some(record.updated_at.clone());
1821    record.state["sessionObjectId"] = json!(object_id);
1822    record.state["commitReceipt"] = completion_state
1823        .get("commitReceipt")
1824        .cloned()
1825        .unwrap_or(Value::Null);
1826    let output = materialize(record, &journal, state.config.provider_cost_compatibility);
1827    let SessionJournal { log, control } = journal;
1828    log.delete_committed().map_err(ApiError::internal)?;
1829    control.delete().map_err(ApiError::internal)?;
1830    Ok(output)
1831}
1832
1833fn fetch_active(state: &AppState, id: &str) -> Result<SessionRecord, ApiError> {
1834    let journal = open_by_id(state, id)?;
1835    latest_lifecycle(&journal).ok_or_else(ApiError::not_found)
1836}
1837
1838fn session_mutation(state: &AppState, id: &str) -> Result<Arc<Mutex<()>>, ApiError> {
1839    let mut sessions = state.session_mutations.lock().map_err(ApiError::internal)?;
1840    sessions.retain(|_, lock| lock.strong_count() > 0);
1841    if let Some(lock) = sessions.get(id).and_then(Weak::upgrade) {
1842        return Ok(lock);
1843    }
1844    let lock = Arc::new(Mutex::new(()));
1845    sessions.insert(id.to_owned(), Arc::downgrade(&lock));
1846    Ok(lock)
1847}
1848
1849fn open_by_id(state: &AppState, id: &str) -> Result<SessionJournal, ApiError> {
1850    validate_session_id(id)?;
1851    let path = state.config.directory.join(format!("{id}.session-log"));
1852    SessionJournal::open(&path).map_err(|error| {
1853        if !path.exists() {
1854            ApiError::not_found()
1855        } else {
1856            ApiError::internal(error)
1857        }
1858    })
1859}
1860
1861fn latest_lifecycle(journal: &SessionJournal) -> Option<SessionRecord> {
1862    journal.projection().lifecycle
1863}
1864
1865fn projected_lifecycle(mut record: SessionRecord) -> SessionRecord {
1866    retain_summary_fields(&mut record.state);
1867    let ControlUpdate::Lifecycle(record) = ControlUpdate::Lifecycle(record).projected() else {
1868        unreachable!("lifecycle projection changed update kind");
1869    };
1870    record
1871}
1872
1873fn append_lifecycle(
1874    journal: &mut SessionJournal,
1875    record: &mut SessionRecord,
1876) -> Result<(), ApiError> {
1877    retain_summary_fields(&mut record.state);
1878    let update = journal
1879        .append_control(ControlUpdate::Lifecycle(record.clone()))
1880        .map_err(ApiError::internal)?;
1881    let ControlUpdate::Lifecycle(projected) = update else {
1882        unreachable!("lifecycle append changed update kind");
1883    };
1884    *record = projected;
1885    Ok(())
1886}
1887
1888fn commands(journal: &SessionJournal) -> BTreeMap<String, SessionCommand> {
1889    journal.projection().commands
1890}
1891
1892fn append_command(journal: &mut SessionJournal, command: &SessionCommand) -> Result<(), ApiError> {
1893    journal
1894        .append_control(ControlUpdate::Command(command.clone()))
1895        .map(|_| ())
1896        .map_err(ApiError::internal)
1897}
1898
1899fn stop_requests(journal: &SessionJournal) -> BTreeMap<String, SessionStopRequest> {
1900    journal.projection().stop_requests
1901}
1902
1903fn append_stop_request(
1904    journal: &mut SessionJournal,
1905    request: &SessionStopRequest,
1906) -> Result<(), ApiError> {
1907    journal
1908        .append_control(ControlUpdate::StopRequest(request.clone()))
1909        .map(|_| ())
1910        .map_err(ApiError::internal)
1911}
1912
1913fn materialize(
1914    mut record: SessionRecord,
1915    journal: &SessionJournal,
1916    provider_cost_compatibility: Option<ProviderCostCompatibility>,
1917) -> SessionRecord {
1918    let log = journal.list();
1919    record.state["sessionId"] = json!(log.header.session_id);
1920    if !record.state.get("transcript").is_some_and(Value::is_array) {
1921        record.state["transcript"] = Value::Array(
1922            log.events
1923                .iter()
1924                .enumerate()
1925                .filter_map(|(position, event)| transcript_entry(position, event))
1926                .collect(),
1927        );
1928    }
1929    if !record.state.get("events").is_some_and(Value::is_array) {
1930        record.state["events"] = serde_json::to_value(&log.events).unwrap_or(Value::Null);
1931    }
1932    let context_state = record
1933        .state
1934        .get("historyIngress")
1935        .filter(|state| state.get("chatendMetadata").is_some())
1936        .unwrap_or(&record.state);
1937    let default_provider_model = provider_cost_compatibility
1938        .and_then(|compatibility| (compatibility.session_model)(context_state))
1939        .or_else(|| {
1940            provider_cost_compatibility
1941                .and_then(|compatibility| (compatibility.session_model)(&record.state))
1942        });
1943    let exact_chatend = context_state
1944        .get("chatendMetadata")
1945        .cloned()
1946        .and_then(|value| serde_json::from_value::<chatend::SessionMetadata>(value).ok())
1947        .and_then(|metadata| match provider_cost_compatibility {
1948            Some(compatibility) => SessionHistoryIntegration::replay(
1949                metadata,
1950                &log,
1951                default_provider_model.as_deref(),
1952                Some(compatibility.estimator),
1953            )
1954            .ok(),
1955            None => SessionHistoryIntegration::replay(metadata, &log, None, None).ok(),
1956        });
1957    if let Some(chatend) = exact_chatend {
1958        let boxes = serde_json::to_value(&chatend.boxes).unwrap_or(Value::Null);
1959        let projection = chatend.projection();
1960        let submitted = chatend.events.iter().rev().find_map(|event| {
1961            let chatend::EventKind::ProviderInputSubmitted { round, context, .. } = &event.kind
1962            else {
1963                return None;
1964            };
1965            Some((event.recorded_at.as_str(), *round, context))
1966        });
1967        let (chatend_text, chatend_text_source, structured_material) = match submitted {
1968            Some((submitted_at, round, submitted)) => (
1969                Value::String(submitted.input.clone()),
1970                Value::String("submitted".into()),
1971                json!({
1972                    "provider":submitted.provider,
1973                    "model":submitted.model,
1974                    "reasoningEffort":submitted.reasoning_effort,
1975                    "baseInstructions":submitted.base_instructions,
1976                    "developerInstructions":submitted.developer_instructions,
1977                    "tools":submitted.tools,
1978                    "round":round,
1979                    "submittedAt":submitted_at,
1980                }),
1981            ),
1982            None => (
1983                Value::String(projection.render()),
1984                Value::String("reconstructed".into()),
1985                Value::Null,
1986            ),
1987        };
1988        let context = serde_json::to_value(projection).unwrap_or(Value::Null);
1989        record.state["boxes"] = boxes.clone();
1990        record.state["context"] = context.clone();
1991        record.state["chatendText"] = chatend_text.clone();
1992        record.state["chatendTextSource"] = chatend_text_source.clone();
1993        record.state["structuredMaterial"] = structured_material.clone();
1994        if let Some(ingress) = record
1995            .state
1996            .get_mut("historyIngress")
1997            .and_then(Value::as_object_mut)
1998        {
1999            ingress.insert("boxes".into(), boxes);
2000            ingress.insert("context".into(), context);
2001            ingress.insert("chatendText".into(), chatend_text);
2002            ingress.insert("chatendTextSource".into(), chatend_text_source);
2003            ingress.insert("structuredMaterial".into(), structured_material);
2004        }
2005    }
2006    record
2007}
2008
2009fn retain_summary_fields(state: &mut Value) {
2010    if state
2011        .get("firstUserMessage")
2012        .and_then(Value::as_str)
2013        .is_some()
2014    {
2015        return;
2016    }
2017    let Some(first_user) = state
2018        .get("transcript")
2019        .and_then(Value::as_array)
2020        .and_then(|transcript| {
2021            transcript
2022                .iter()
2023                .find(|entry| entry.get("role").and_then(Value::as_str) == Some("user"))
2024        })
2025        .and_then(|entry| entry.get("content"))
2026        .and_then(Value::as_str)
2027    else {
2028        return;
2029    };
2030    state["firstUserMessage"] = Value::String(first_user.chars().take(512).collect());
2031}
2032
2033fn summary_state(control: &Value) -> Value {
2034    json!({
2035        "sessionType":control.get("sessionType"),
2036        "channel":control.get("channel"),
2037        "freeTime":control.get("freeTime"),
2038        "orchestration":control.get("orchestration"),
2039        "ingressSource":control.get("ingressSource"),
2040        "firstUserMessage":control.get("firstUserMessage"),
2041        "boxCount":control.get("boxCount"),
2042        "eventCount":control.get("eventCount"),
2043        "pendingTurn":control.get("pendingTurn").cloned().unwrap_or(Value::Bool(false)),
2044    })
2045}
2046
2047fn persisted_context_kind(event: &kcode_session_log::SessionEvent) -> Option<Value> {
2048    serde_json::from_str::<Value>(&event.text)
2049        .ok()?
2050        .get("kind")
2051        .cloned()
2052}
2053
2054fn display_text(event: &kcode_session_log::SessionEvent) -> String {
2055    persisted_context_kind(event)
2056        .and_then(|kind| {
2057            (kind.get("type").and_then(Value::as_str) == Some("box_created"))
2058                .then(|| {
2059                    kind.get("content")
2060                        .and_then(|content| content.get("text"))
2061                        .and_then(Value::as_str)
2062                        .map(str::to_owned)
2063                })
2064                .flatten()
2065        })
2066        .unwrap_or_else(|| event.text.clone())
2067}
2068
2069fn transcript_entry(position: usize, event: &kcode_session_log::SessionEvent) -> Option<Value> {
2070    let kind = persisted_context_kind(event);
2071    let box_content = kind
2072        .as_ref()
2073        .filter(|kind| kind.get("type").and_then(Value::as_str) == Some("box_created"))
2074        .and_then(|kind| kind.get("content"));
2075    let metadata = box_content
2076        .and_then(|content| content.get("metadata"))
2077        .filter(|value| value.is_object());
2078    let role = match event.role {
2079        Role::UserMessage => "user",
2080        Role::KennedyMessage => "kennedy",
2081        Role::SystemError => "system",
2082        Role::SystemMessage => (box_content?
2083            .get("metadata")
2084            .and_then(|metadata| metadata.get("transcriptRole"))
2085            .and_then(Value::as_str)
2086            == Some("system"))
2087        .then_some("system")?,
2088        _ => return None,
2089    };
2090    let mut item = json!({
2091        "role":role,
2092        "content":display_text(event),
2093        "boxId":position + 1,
2094    });
2095    if let Some(objects) = box_content
2096        .and_then(|content| content.get("objects"))
2097        .filter(|value| value.is_array())
2098    {
2099        item["objects"] = objects.clone();
2100    }
2101    if let Some(metadata) = metadata {
2102        for key in ["inputKind", "externalEventId"] {
2103            if let Some(value) = metadata.get(key) {
2104                item[key] = value.clone();
2105            }
2106        }
2107        if let Some(attachments) = metadata.get("attachments").filter(|value| value.is_array()) {
2108            item["attachments"] = attachments.clone();
2109        } else if let Some(media) = metadata.get("media").filter(|value| value.is_object()) {
2110            item["attachments"] = json!([media]);
2111        }
2112    }
2113    Some(item)
2114}
2115
2116fn journal_paths(directory: &FilePath) -> Result<Vec<PathBuf>, ApiError> {
2117    let mut paths = std::fs::read_dir(directory)
2118        .map_err(ApiError::internal)?
2119        .filter_map(Result::ok)
2120        .map(|entry| entry.path())
2121        .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("session-log"))
2122        .collect::<Vec<_>>();
2123    paths.sort();
2124    Ok(paths)
2125}
2126
2127fn listed_session_parts(path: &FilePath) -> anyhow::Result<(&FilePath, &str)> {
2128    ensure!(
2129        path.extension().and_then(|value| value.to_str()) == Some("session-log"),
2130        "{} is not a session-log path",
2131        path.display()
2132    );
2133    let directory = path.parent().unwrap_or_else(|| FilePath::new("."));
2134    let id = path
2135        .file_stem()
2136        .and_then(|value| value.to_str())
2137        .context("session-log filename is not valid UTF-8")?;
2138    Ok((directory, id))
2139}
2140
2141fn open_listed_control(path: &FilePath) -> anyhow::Result<Option<SessionControl>> {
2142    let (directory, id) = listed_session_parts(path)?;
2143    let control = SessionControl::open(directory, id, OpenMode::ExistingOnly)?;
2144    if !path.exists() {
2145        return Ok(None);
2146    }
2147    Ok(control)
2148}
2149
2150fn open_listed_control_projections(
2151    paths: Vec<PathBuf>,
2152) -> Result<Vec<ControlProjection>, ApiError> {
2153    let mut projections = Vec::with_capacity(paths.len());
2154    for path in paths {
2155        let Some(control) = open_listed_control(&path).map_err(ApiError::internal)? else {
2156            continue;
2157        };
2158        let projection = control.projection();
2159        if projection.lifecycle.is_some() {
2160            projections.push(projection);
2161        }
2162    }
2163    Ok(projections)
2164}
2165
2166#[cfg(test)]
2167fn open_listed_journals(paths: Vec<PathBuf>) -> Result<Vec<SessionJournal>, ApiError> {
2168    let mut journals = Vec::new();
2169    for path in paths {
2170        match SessionJournal::open_existing(&path) {
2171            Ok(Some(journal)) => journals.push(journal),
2172            Ok(None) => {}
2173            Err(_) if !path.exists() => {}
2174            Err(error) => return Err(ApiError::internal(error)),
2175        }
2176    }
2177    Ok(journals)
2178}
2179
2180fn read_completed_ids(path: &FilePath) -> anyhow::Result<Vec<String>> {
2181    Ok(read_completion_receipts(path)?
2182        .into_iter()
2183        .map(|receipt| receipt.session_object_id)
2184        .collect())
2185}
2186
2187fn read_completion_receipts(path: &FilePath) -> anyhow::Result<Vec<CompletionReceipt>> {
2188    let file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
2189    let mut receipts = Vec::new();
2190    let mut seen = HashSet::new();
2191    for line in BufReader::new(file).lines() {
2192        let line = line?;
2193        let line = line.trim();
2194        if line.is_empty() {
2195            continue;
2196        }
2197        let receipt = if line.starts_with('{') {
2198            serde_json::from_str::<CompletionReceipt>(line)
2199                .context("decoding Session History completion receipt")?
2200        } else {
2201            CompletionReceipt {
2202                transaction_id: None,
2203                session_object_id: line.to_owned(),
2204                session_id: None,
2205                session_type: None,
2206                created_at: None,
2207                committed_at: None,
2208                ingress_source: None,
2209                node_ids: BTreeMap::new(),
2210                object_ids: BTreeMap::new(),
2211            }
2212        };
2213        if seen.insert(receipt.session_object_id.clone()) {
2214            receipts.push(receipt);
2215        }
2216    }
2217    Ok(receipts)
2218}
2219
2220#[cfg(test)]
2221fn append_completed_id(path: &FilePath, id: &str) -> anyhow::Result<()> {
2222    append_completion_receipt(
2223        path,
2224        &CompletionReceipt {
2225            transaction_id: None,
2226            session_object_id: id.into(),
2227            session_id: None,
2228            session_type: None,
2229            created_at: None,
2230            committed_at: None,
2231            ingress_source: None,
2232            node_ids: BTreeMap::new(),
2233            object_ids: BTreeMap::new(),
2234        },
2235    )
2236}
2237
2238fn append_completion_receipt(path: &FilePath, receipt: &CompletionReceipt) -> anyhow::Result<()> {
2239    if read_completed_ids(path)?
2240        .iter()
2241        .any(|existing| existing == &receipt.session_object_id)
2242    {
2243        return Ok(());
2244    }
2245    let mut file = OpenOptions::new().append(true).open(path)?;
2246    writeln!(file, "{}", serde_json::to_string(receipt)?)?;
2247    file.flush()?;
2248    file.sync_data()?;
2249    Ok(())
2250}
2251
2252fn create_private_directory(path: &FilePath) -> anyhow::Result<()> {
2253    if path.is_dir() {
2254        return Ok(());
2255    }
2256    let mut builder = std::fs::DirBuilder::new();
2257    builder.recursive(true);
2258    #[cfg(unix)]
2259    {
2260        use std::os::unix::fs::DirBuilderExt as _;
2261        builder.mode(0o700);
2262    }
2263    builder
2264        .create(path)
2265        .with_context(|| format!("creating {}", path.display()))?;
2266    let parent = path
2267        .parent()
2268        .filter(|parent| !parent.as_os_str().is_empty())
2269        .unwrap_or_else(|| FilePath::new("."));
2270    sync_directory(parent)
2271}
2272
2273fn sync_directory(path: &FilePath) -> anyhow::Result<()> {
2274    File::open(path)
2275        .with_context(|| format!("opening directory {} for sync", path.display()))?
2276        .sync_all()
2277        .with_context(|| format!("syncing directory {}", path.display()))
2278}
2279
2280fn validate_started_at(value: &str) -> Result<(), ApiError> {
2281    DateTime::parse_from_rfc3339(value)
2282        .map(|_| ())
2283        .map_err(|_| ApiError::bad("started_at must be an RFC 3339 timestamp"))
2284}
2285
2286fn validate_idempotency(value: &str) -> Result<(), ApiError> {
2287    if value.is_empty() || value.len() > 255 {
2288        return Err(ApiError::bad(
2289            "idempotency_id must contain between 1 and 255 bytes",
2290        ));
2291    }
2292    Ok(())
2293}
2294
2295fn validate_session_id(value: &str) -> Result<(), ApiError> {
2296    Uuid::parse_str(value)
2297        .map(|_| ())
2298        .map_err(|_| ApiError::bad("invalid session ID"))
2299}
2300
2301fn require_version(record: &SessionRecord, expected: i64) -> Result<(), ApiError> {
2302    if record.version != expected {
2303        return Err(ApiError::conflict(format!(
2304            "Expected session version {expected}, found {}.",
2305            record.version
2306        )));
2307    }
2308    Ok(())
2309}
2310
2311fn now() -> String {
2312    Utc::now().to_rfc3339()
2313}
2314
2315#[cfg(test)]
2316mod tests {
2317    use std::time::{SystemTime, UNIX_EPOCH};
2318
2319    use super::*;
2320
2321    fn root(label: &str) -> PathBuf {
2322        std::env::temp_dir().join(format!(
2323            "kennedy-session-history-{label}-{}-{}",
2324            std::process::id(),
2325            SystemTime::now()
2326                .duration_since(UNIX_EPOCH)
2327                .unwrap()
2328                .as_nanos()
2329        ))
2330    }
2331
2332    fn service(label: &str) -> SessionHistory {
2333        let root = root(label);
2334        std::fs::create_dir_all(&root).unwrap();
2335        SessionHistory::open(Config {
2336            directory: root.join("sessions"),
2337            completed_list: root.join("session-history.txt"),
2338            provider_cost_compatibility: None,
2339        })
2340        .unwrap()
2341    }
2342
2343    async fn start(service: &SessionHistory, idempotency_id: &str) -> SessionRecord {
2344        service
2345            .start(StartSession {
2346                idempotency_id: idempotency_id.into(),
2347                started_at: "2026-07-23T00:00:00Z".into(),
2348                session_type: "conversation".into(),
2349                duration_minutes: None,
2350                custom_prompt: None,
2351            })
2352            .await
2353            .unwrap()
2354            .value
2355    }
2356
2357    #[tokio::test]
2358    async fn managed_log_and_control_creation_remain_coordinated() {
2359        let service = service("coordinated");
2360        let record = start(&service, "start-1").await;
2361        let mut journal = open_by_id(&service.state, &record.id).unwrap();
2362        journal
2363            .log
2364            .add_event(Role::SystemError, "The message exceeded capacity.")
2365            .unwrap();
2366        drop(journal);
2367
2368        let command = service
2369            .enqueue(
2370                &record.id,
2371                NewCommand {
2372                    idempotency_id: "message-1".into(),
2373                    kind: "message".into(),
2374                    payload: json!({"text":"hello"}),
2375                },
2376            )
2377            .await
2378            .unwrap()
2379            .value;
2380        assert_eq!(command.status, "pending");
2381        assert_eq!(
2382            service.get(&record.id).await.unwrap().state["transcript"][0]["content"],
2383            "The message exceeded capacity."
2384        );
2385        assert_eq!(
2386            std::fs::read_dir(&service.state.config.directory)
2387                .unwrap()
2388                .count(),
2389            2
2390        );
2391    }
2392
2393    #[tokio::test]
2394    async fn projected_state_is_rebuilt_from_the_preserved_transcript() {
2395        let service = service("transcript-preservation");
2396        let record = start(&service, "start-1").await;
2397        let mut journal = open_by_id(&service.state, &record.id).unwrap();
2398        journal
2399            .log
2400            .add_event(Role::UserMessage, "hello from the log")
2401            .unwrap();
2402        drop(journal);
2403
2404        let checkpointed = service
2405            .checkpoint(
2406                &record.id,
2407                Checkpoint {
2408                    expected_version: record.version,
2409                    state: json!({
2410                        "sessionId":record.id,
2411                        "sessionType":"conversation",
2412                        "boxes":{"1":{"presentation":"discard"}},
2413                        "context":{"presentation":"discard"},
2414                        "chatendText":"discard",
2415                        "historyIngress":{"format":"kennedy-chatend","version":1}
2416                    }),
2417                    user_activity: false,
2418                },
2419            )
2420            .await
2421            .unwrap();
2422
2423        assert!(checkpointed.state.get("boxes").is_none());
2424        assert!(checkpointed.state.get("context").is_none());
2425        assert!(checkpointed.state.get("chatendText").is_none());
2426        assert_eq!(
2427            checkpointed.state["transcript"][0]["content"],
2428            "hello from the log"
2429        );
2430        assert_eq!(
2431            checkpointed.state["historyIngress"]["format"],
2432            "kennedy-chatend"
2433        );
2434    }
2435
2436    #[tokio::test]
2437    async fn command_and_stop_policy_remain_in_session_history() {
2438        let service = service("command-stop");
2439        let record = start(&service, "start-1").await;
2440        let command = service
2441            .enqueue(
2442                &record.id,
2443                NewCommand {
2444                    idempotency_id: "message-1".into(),
2445                    kind: "message".into(),
2446                    payload: json!({"text":"hello"}),
2447                },
2448            )
2449            .await
2450            .unwrap()
2451            .value;
2452        service.claim_command(&command.id).await.unwrap();
2453
2454        let stop = service
2455            .request_stop(
2456                &record.id,
2457                NewStopRequest {
2458                    idempotency_id: "stop-1".into(),
2459                    scope: "turn".into(),
2460                },
2461            )
2462            .await
2463            .unwrap()
2464            .value;
2465        assert_eq!(stop.scope, "turn");
2466        assert_eq!(
2467            service.get(&record.id).await.unwrap().version,
2468            record.version
2469        );
2470        assert!(service.command_heads().await.unwrap()[0].cancel_requested);
2471
2472        let completed = service
2473            .complete_stop(
2474                &stop.id,
2475                StopOutcome {
2476                    outcome: json!({"status":"stopped"}),
2477                },
2478            )
2479            .await
2480            .unwrap();
2481        assert_eq!(completed.status, "complete");
2482        assert!(service.stop_heads().await.unwrap().is_empty());
2483    }
2484
2485    #[tokio::test]
2486    async fn enumeration_skips_logs_without_lifecycle_without_replay() {
2487        let service = service("control-first-enumeration");
2488        let id = Uuid::new_v4().to_string();
2489        let directory = &service.state.config.directory;
2490        std::fs::write(
2491            directory.join(format!("{id}.session-log")),
2492            b"not a valid session log",
2493        )
2494        .unwrap();
2495        SessionControl::open(directory, &id, OpenMode::CreateNew)
2496            .unwrap()
2497            .unwrap();
2498
2499        assert!(service.list().await.unwrap().is_empty());
2500        assert!(service.command_heads().await.unwrap().is_empty());
2501        assert!(service.stop_heads().await.unwrap().is_empty());
2502    }
2503
2504    #[tokio::test]
2505    async fn session_summaries_use_bounded_control_state_without_log_replay() {
2506        let service = service("control-only-summaries");
2507        let record = start(&service, "start-1").await;
2508        let id = record.id.clone();
2509        let mut state = record.state;
2510        state["transcript"] = json!([{"role":"user","content":"x".repeat(600)}]);
2511        state["boxCount"] = json!(2);
2512        state["eventCount"] = json!(3);
2513        service
2514            .checkpoint(
2515                &id,
2516                Checkpoint {
2517                    expected_version: record.version,
2518                    state,
2519                    user_activity: true,
2520                },
2521            )
2522            .await
2523            .unwrap();
2524        std::fs::write(
2525            service
2526                .state
2527                .config
2528                .directory
2529                .join(format!("{id}.session-log")),
2530            b"not a valid session log",
2531        )
2532        .unwrap();
2533
2534        let listed = service.list().await.unwrap();
2535        assert_eq!(listed.len(), 1);
2536        assert_eq!(listed[0].state["firstUserMessage"], "x".repeat(512));
2537        assert_eq!(listed[0].state["boxCount"], 2);
2538        assert_eq!(listed[0].state["eventCount"], 3);
2539    }
2540
2541    #[tokio::test]
2542    async fn control_queries_do_not_replay_session_logs() {
2543        let service = service("control-only-heads");
2544        let record = start(&service, "start-1").await;
2545        let command = service
2546            .enqueue(
2547                &record.id,
2548                NewCommand {
2549                    idempotency_id: "message-1".into(),
2550                    kind: "message".into(),
2551                    payload: json!({"text":"hello"}),
2552                },
2553            )
2554            .await
2555            .unwrap()
2556            .value;
2557        let stop = service
2558            .request_stop(
2559                &record.id,
2560                NewStopRequest {
2561                    idempotency_id: "stop-1".into(),
2562                    scope: "session".into(),
2563                },
2564            )
2565            .await
2566            .unwrap()
2567            .value;
2568        std::fs::write(
2569            service
2570                .state
2571                .config
2572                .directory
2573                .join(format!("{}.session-log", record.id)),
2574            b"not a valid session log",
2575        )
2576        .unwrap();
2577
2578        let command_heads = service.command_heads().await.unwrap();
2579        assert_eq!(command_heads.len(), 1);
2580        assert_eq!(command_heads[0].id, command.id);
2581        let stop_heads = service.stop_heads().await.unwrap();
2582        assert_eq!(stop_heads.len(), 1);
2583        assert_eq!(stop_heads[0].id, stop.id);
2584        let listed = service.list().await.unwrap();
2585        assert_eq!(listed.len(), 1);
2586        assert!(listed[0].state["firstUserMessage"].is_null());
2587        assert!(listed[0].state["boxCount"].is_null());
2588        assert!(listed[0].state["eventCount"].is_null());
2589    }
2590
2591    #[tokio::test]
2592    async fn completion_synchronizes_receipt_before_live_file_cleanup() {
2593        let service = service("completion-order");
2594        let record = start(&service, "start-1").await;
2595        let id = record.id.clone();
2596        let mut state = record.state;
2597        state["historyIngress"] = json!({
2598            "completed":true,
2599            "sessionObjectId":"A1234567",
2600            "commitReceipt":{
2601                "transactionId":"T1234567",
2602                "sessionObjectId":"A1234567",
2603                "nodeIds":{},
2604                "objectIds":{}
2605            }
2606        });
2607
2608        service
2609            .complete(
2610                &id,
2611                Checkpoint {
2612                    expected_version: record.version,
2613                    state,
2614                    user_activity: false,
2615                },
2616            )
2617            .await
2618            .unwrap();
2619
2620        let receipts = read_completion_receipts(&service.state.config.completed_list).unwrap();
2621        assert_eq!(receipts[0].session_object_id, "A1234567");
2622        assert_eq!(
2623            std::fs::read_dir(&service.state.config.directory)
2624                .unwrap()
2625                .count(),
2626            0
2627        );
2628    }
2629
2630    #[tokio::test]
2631    async fn listing_tolerates_completion_after_path_enumeration() {
2632        let service = service("concurrent-list");
2633        let record = start(&service, "start-1").await;
2634        let id = record.id.clone();
2635        let listed_paths = journal_paths(&service.state.config.directory).unwrap();
2636
2637        let mut state = record.state;
2638        state["sessionObjectId"] = json!("A1234567");
2639        service
2640            .complete(
2641                &id,
2642                Checkpoint {
2643                    expected_version: record.version,
2644                    state,
2645                    user_activity: false,
2646                },
2647            )
2648            .await
2649            .unwrap();
2650
2651        assert!(open_listed_journals(listed_paths).unwrap().is_empty());
2652        let listed = service.list().await.unwrap();
2653        assert_eq!(listed.len(), 1);
2654        assert_eq!(listed[0].phase, "complete");
2655        assert_eq!(listed[0].state["sessionObjectId"], "A1234567");
2656    }
2657
2658    #[tokio::test]
2659    async fn ingress_failures_wait_for_manual_retry_and_drop_attempt_state() {
2660        let service = service("ingress-retry");
2661        let created = start(&service, "start-1").await;
2662        let mut record = service
2663            .request_ingress(
2664                &created.id,
2665                Checkpoint {
2666                    expected_version: created.version,
2667                    state: created.state,
2668                    user_activity: false,
2669                },
2670            )
2671            .await
2672            .unwrap();
2673
2674        for _ in 0..RETAINED_INGRESS_FAILURES + 1 {
2675            record = service
2676                .start_ingress(
2677                    &record.id,
2678                    StartIngress {
2679                        expected_version: record.version,
2680                        provenance_id: "session:test".into(),
2681                    },
2682                )
2683                .await
2684                .unwrap();
2685            record = service
2686                .fail_ingress(
2687                    &record.id,
2688                    IngressFailure {
2689                        expected_version: record.version,
2690                        stage: "model_loop".into(),
2691                        code: Some("ingress_error".into()),
2692                        message: "transient failure".into(),
2693                        rounds_used: None,
2694                        context_tokens: None,
2695                        context_window_tokens: None,
2696                    },
2697                )
2698                .await
2699                .unwrap();
2700            assert_eq!(record.phase, "ingress_failed");
2701            assert_eq!(record.ingress_failure_count, 1);
2702            let mut retry_state = record.state.clone();
2703            retry_state["historyIngress"] = json!({"roundsUsed":17});
2704            record = service
2705                .retry_ingress(
2706                    &record.id,
2707                    RetryIngress {
2708                        expected_version: record.version,
2709                        state: retry_state,
2710                    },
2711                )
2712                .await
2713                .unwrap();
2714            assert_eq!(record.phase, "ingress_pending");
2715            assert!(record.state.get("historyIngress").is_none());
2716        }
2717        assert_eq!(
2718            record.ingress_failures.as_array().unwrap().len(),
2719            RETAINED_INGRESS_FAILURES
2720        );
2721    }
2722
2723    #[tokio::test]
2724    async fn interrupted_ingress_requires_manual_retry_after_startup_repair() {
2725        let service = service("ingress-interrupted");
2726        let created = start(&service, "start-1").await;
2727        let pending = service
2728            .request_ingress(
2729                &created.id,
2730                Checkpoint {
2731                    expected_version: created.version,
2732                    state: created.state,
2733                    user_activity: false,
2734                },
2735            )
2736            .await
2737            .unwrap();
2738        service
2739            .start_ingress(
2740                &pending.id,
2741                StartIngress {
2742                    expected_version: pending.version,
2743                    provenance_id: "session:test".into(),
2744                },
2745            )
2746            .await
2747            .unwrap();
2748
2749        assert_eq!(
2750            service.release_interrupted_ingress().await.unwrap(),
2751            vec![pending.id.clone()]
2752        );
2753        let failed = service.get(&pending.id).await.unwrap();
2754        assert_eq!(failed.phase, "ingress_failed");
2755        assert_eq!(failed.ingress_failures[0]["code"], "ingress_interrupted");
2756    }
2757
2758    #[tokio::test]
2759    async fn historical_completion_lines_remain_readable() {
2760        let service = service("completed");
2761        append_completed_id(&service.state.config.completed_list, "A1234567").unwrap();
2762        let listed = service.list().await.unwrap();
2763        assert_eq!(listed[0].state["sessionObjectId"], "A1234567");
2764        assert_eq!(
2765            listed[0].state["commitReceipt"]["sessionObjectId"],
2766            "A1234567"
2767        );
2768    }
2769}