Skip to main content

codewhale_core/
lib.rs

1pub mod context_reference;
2pub mod fragments;
3pub mod ids;
4pub mod journal;
5pub mod prefix_cache;
6pub mod request;
7pub mod role;
8pub mod secret_eq;
9pub mod session;
10pub mod tool_parser;
11
12pub use context_reference::{
13    ContextReference, ContextReferenceKind, ContextReferenceSource, MediaAttachmentReference,
14    media_attachment_references,
15};
16
17use codewhale_config::{ConfigToml, ProviderKind};
18use codewhale_hooks::HookDispatcher;
19use codewhale_state::StateStore;
20
21/// Compatibility configuration and hooks.
22///
23/// Conversation execution and durable history belong to the held canonical
24/// RuntimeThreadManager/Engine. Legacy State data is retained for read-only
25/// recovery and bound alias publication, never as a second transcript writer.
26pub struct Runtime {
27    pub config: ConfigToml,
28    state: StateStore,
29    pub hooks: HookDispatcher,
30}
31
32impl Runtime {
33    pub fn new(config: ConfigToml, state: StateStore, hooks: HookDispatcher) -> Self {
34        Self {
35            config,
36            state,
37            hooks,
38        }
39    }
40
41    /// Existing compatibility data and receipts; no transcript controller.
42    pub fn state_store(&self) -> &StateStore {
43        &self.state
44    }
45
46    pub fn update_config(&mut self, config: ConfigToml) {
47        self.config = config;
48    }
49
50    /// Returns the default model provider from the resolved configuration.
51    pub fn provider_default(&self) -> ProviderKind {
52        self.config.provider
53    }
54}
55
56/// How many leading entries of `offered` repeat the end of `persisted`: the
57/// longest suffix of `persisted` that is also a prefix of `offered`.
58/// Longest persisted suffix repeated by an offered history prefix. Linear
59/// work preserves genuine repeated messages without an unbounded nested scan.
60pub fn persisted_overlap<T: PartialEq>(persisted: &[T], offered: &[T]) -> usize {
61    if offered.is_empty() {
62        return 0;
63    }
64    let mut failure = vec![0; offered.len()];
65    for index in 1..offered.len() {
66        let mut matched = failure[index - 1];
67        while matched > 0 && offered[index] != offered[matched] {
68            matched = failure[matched - 1];
69        }
70        if offered[index] == offered[matched] {
71            matched += 1;
72        }
73        failure[index] = matched;
74    }
75    let mut matched = 0;
76    for item in persisted {
77        if matched == offered.len() {
78            matched = failure[matched - 1];
79        }
80        while matched > 0 && *item != offered[matched] {
81            matched = failure[matched - 1];
82        }
83        if *item == offered[matched] {
84            matched += 1;
85        }
86    }
87    matched
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    use uuid::Uuid;
94
95    fn temp_core_state(name: &str) -> StateStore {
96        let dir =
97            std::env::temp_dir().join(format!("codewhale-core-{name}-{}", Uuid::new_v4().simple()));
98        std::fs::create_dir_all(&dir).expect("create temp state dir");
99        StateStore::open(Some(dir.join("state.db"))).expect("open state store")
100    }
101
102    #[test]
103    fn runtime_bookkeeping_keeps_the_legacy_store_read_only() {
104        let store = temp_core_state("read-only-runtime");
105        let before = store.list_threads(Default::default()).unwrap();
106        let mut runtime = Runtime::new(ConfigToml::default(), store, HookDispatcher::default());
107        runtime.update_config(ConfigToml::default());
108        assert_eq!(
109            runtime
110                .state_store()
111                .list_threads(Default::default())
112                .unwrap()
113                .len(),
114            before.len()
115        );
116        let reopened = Runtime::new(
117            runtime.config.clone(),
118            runtime.state_store().clone(),
119            HookDispatcher::default(),
120        );
121        assert!(
122            reopened
123                .state_store()
124                .list_threads(Default::default())
125                .unwrap()
126                .is_empty()
127        );
128    }
129}