Skip to main content

lash_core/runtime/
lifecycle.rs

1use super::*;
2
3impl LashRuntime {
4    pub fn unregister_plugin_session(&self) -> Result<(), crate::PluginError> {
5        if let Some(session) = self.session.as_ref() {
6            session
7                .plugins()
8                .host()
9                .unregister_session(&self.state.session_id)?;
10        }
11        Ok(())
12    }
13
14    pub(super) async fn from_host_state(
15        policy: SessionPolicy,
16        host: RuntimeHost,
17        services: RuntimeServices,
18        mut state: RuntimeSessionState,
19    ) -> Result<Self, SessionError> {
20        if state.session_id.is_empty() {
21            state.session_id = uuid::Uuid::new_v4().to_string();
22        }
23        // Defaulted state (e.g. `RuntimeSessionState::default()` used
24        // by fresh-session constructors) carries an empty policy.
25        // Fill it in from the caller's policy so tests and hosts that
26        // pass a real policy alongside default state don't trip the explicit
27        // model-spec guard below.
28        let state_policy_was_unconfigured = state.policy.recorded_provider_id().is_empty()
29            && state.policy.model.id.trim().is_empty();
30        if state_policy_was_unconfigured {
31            state.policy = policy.clone();
32        }
33        state.ensure_agent_frame_initialized();
34        let state_policy = state.policy.clone();
35        if let Some(frame) = state.current_agent_frame_mut()
36            && frame.assignment.policy.recorded_provider_id().is_empty()
37            && frame.assignment.policy.model.id.trim().is_empty()
38        {
39            frame.assignment.policy = state_policy;
40        }
41        state.policy = state.effective_policy().clone();
42        state.protocol_turn_options = state.effective_protocol_turn_options().clone();
43        normalize_session_graph(&mut state);
44        let policy = state.effective_policy().clone();
45        if policy.model.id.trim().is_empty() {
46            return Err(SessionError::Protocol(
47                "session policy missing model spec; hosts must supply explicit model metadata"
48                    .to_string(),
49            ));
50        }
51        let mut host = host;
52        // When a persistent backend is wired in, wrap the attachment
53        // store so every `put` records a write-ahead intent row first.
54        // Crashes between put and the next turn commit then surface as
55        // uncommitted manifest rows that GC can reconcile. Ephemeral
56        // (no-store) runtimes use the inner store directly — there's
57        // nothing to reconcile against.
58        if let Some(store) = services.store.clone() {
59            let manifest: Arc<dyn crate::AttachmentManifest> =
60                Arc::new(crate::attachments::PersistenceManifestAdapter(store));
61            let scoped: Arc<dyn crate::AttachmentStore> =
62                Arc::new(crate::SessionScopedAttachmentStore::new(
63                    Arc::clone(&host.core.durability.attachment_store),
64                    manifest,
65                    state.session_id.clone(),
66                ));
67            host.core.durability.attachment_store = scoped;
68        }
69        let services =
70            services.with_attachment_store(Arc::clone(&host.core.durability.attachment_store));
71        let services = services.with_lashlang_artifact_store(Arc::clone(
72            &host.core.durability.lashlang_artifact_store,
73        ));
74        let mut session = Session::new(services.clone(), &state.session_id).await?;
75        if let Some(tool_state) = state.tool_state_snapshot.clone() {
76            // Cold rebuild restores the exact persisted tool surface, adopting
77            // the snapshot's generation. `apply_state` (a delta-apply that
78            // requires `snapshot.generation == base` and bumps) would reject a
79            // session whose surface reached generation ≥ 2 onto a fresh base-1
80            // registry — the worker-rebuild / restart divergence. `restore_state`
81            // adopts the snapshot's generation wholesale, so any generation
82            // rebuilds.
83            session
84                .plugins()
85                .tool_registry()
86                .restore_state(tool_state)
87                .map_err(|err| SessionError::Protocol(err.to_string()))?;
88        }
89        session.refresh_tool_surface().await?;
90        if let Some(snapshot) = state.plugin_snapshot.clone() {
91            session
92                .plugins()
93                .restore(&snapshot)
94                .map_err(|err| SessionError::Protocol(err.to_string()))?;
95        }
96        let protocol_session = Arc::clone(session.plugins().protocol_session());
97        let session_id = state.session_id.clone();
98        protocol_session
99            .restore_session(
100                crate::plugin::ProtocolSessionContext::new(&mut session, &session_id),
101                &state,
102            )
103            .await?;
104        state.discard_runtime_snapshots();
105        session
106            .plugins()
107            .emit_runtime_event(crate::PluginLifecycleEvent::SessionRestored(
108                crate::SessionReadView::from_persisted_state(&state),
109            ))
110            .await;
111        let protocol_turn_options = state.protocol_turn_options.clone();
112        Ok(Self {
113            session: Some(session),
114            policy,
115            host,
116            services,
117            state,
118            runtime_scope_id: Arc::<str>::from(uuid::Uuid::new_v4().to_string()),
119            managed_sessions: Arc::new(Mutex::new(HashMap::new())),
120            managed_turns: Arc::new(Mutex::new(HashMap::new())),
121            protocol_turn_options,
122            shared_token_ledger: Arc::new(std::sync::Mutex::new(Vec::new())),
123            process_sync_needed: Arc::new(AtomicBool::new(false)),
124            turn_phase_probe: None,
125            residency: Residency::default(),
126        })
127    }
128
129    /// Build a runtime for an embedded host with no background worker support.
130    pub async fn from_embedded_state(
131        policy: SessionPolicy,
132        host: EmbeddedRuntimeHost,
133        services: RuntimeServices,
134        state: RuntimeSessionState,
135    ) -> Result<Self, SessionError> {
136        Self::from_host_state(policy, host.into(), services, state).await
137    }
138
139    /// Build a runtime for a host that supports background plugin work.
140    pub async fn from_background_state(
141        policy: SessionPolicy,
142        host: ProcessRuntimeHost,
143        services: RuntimeServices,
144        state: RuntimeSessionState,
145    ) -> Result<Self, SessionError> {
146        Self::from_host_state(policy, host.into(), services, state).await
147    }
148
149    /// Build a runtime for an embedded host with persistent store support.
150    pub async fn from_persistent_embedded_state(
151        policy: SessionPolicy,
152        host: EmbeddedRuntimeHost,
153        services: PersistentRuntimeServices,
154        state: RuntimeSessionState,
155    ) -> Result<Self, SessionError> {
156        Self::from_host_state(policy, host.into(), services.into_runtime_services(), state).await
157    }
158
159    /// Build a runtime for a background-capable host with persistent store support.
160    pub async fn from_persistent_background_state(
161        policy: SessionPolicy,
162        host: ProcessRuntimeHost,
163        services: PersistentRuntimeServices,
164        state: RuntimeSessionState,
165    ) -> Result<Self, SessionError> {
166        Self::from_host_state(policy, host.into(), services.into_runtime_services(), state).await
167    }
168
169    /// Assemble a runtime from already-resolved parts: the single place that maps
170    /// `(store, process_registry)` to the right host/services constructor, applies
171    /// residency, and stamps it onto the runtime.
172    ///
173    /// Every construction path — the live open (`from_environment`), the worker
174    /// rebuild (`EmbeddedRuntimeBuilder::build`), and child-session
175    /// materialization — routes through here so the store/registry wiring and
176    /// residency cannot drift between them. That drift previously shipped: the
177    /// worker rebuild silently kept the full graph and skipped the persisted
178    /// tool-surface restore that the live path applied.
179    pub(crate) async fn assemble_runtime(
180        policy: SessionPolicy,
181        embedded_host: EmbeddedRuntimeHost,
182        plugin_session: Arc<crate::PluginSession>,
183        store: Option<Arc<dyn crate::store::RuntimePersistence>>,
184        process_registry: Option<Arc<dyn ProcessRegistry>>,
185        mut state: RuntimeSessionState,
186        residency: Residency,
187    ) -> Result<Self, SessionError> {
188        // ActivePathOnly without a store is a data-loss footgun: trimming drops
189        // orphans from RAM with nowhere to reload them from.
190        if matches!(residency, Residency::ActivePathOnly) && store.is_none() {
191            return Err(SessionError::Protocol(
192                "Residency::ActivePathOnly requires a persistent store — \
193                 without one, trimmed orphans are irrecoverable"
194                    .to_string(),
195            ));
196        }
197        // Heal FIRST (against the full resident set), then trim to the residency.
198        // `from_host_state` normalizes again, which is safe on a trimmed graph.
199        normalize_session_graph(&mut state);
200        apply_residency_on_load(&mut state, residency);
201        let mut runtime = match (store, process_registry) {
202            (Some(store), Some(registry)) => {
203                let host = ProcessRuntimeHost::new(embedded_host, registry);
204                let services = PersistentRuntimeServices::new(plugin_session, store);
205                Self::from_persistent_background_state(policy, host, services, state).await?
206            }
207            (Some(store), None) => {
208                let services = PersistentRuntimeServices::new(plugin_session, store);
209                Self::from_persistent_embedded_state(policy, embedded_host, services, state).await?
210            }
211            (None, Some(registry)) => {
212                let host = ProcessRuntimeHost::new(embedded_host, registry);
213                let services = RuntimeServices::new(plugin_session);
214                Self::from_background_state(policy, host, services, state).await?
215            }
216            (None, None) => {
217                let services = RuntimeServices::new(plugin_session);
218                Self::from_embedded_state(policy, embedded_host, services, state).await?
219            }
220        };
221        runtime.residency = residency;
222        Ok(runtime)
223    }
224
225    /// Embedder-preferred constructor: build a `LashRuntime` from a
226    /// shared `RuntimeEnvironment`.
227    ///
228    /// Everything expensive (plugin factories, HTTP client pool, prompt
229    /// template, path resolver) lives on the environment and is
230    /// reused across every runtime the embedder builds. This call is
231    /// O(plugin-session-registration + state-hydration), not
232    /// O(full-infrastructure-init).
233    ///
234    /// * `env` — the shared environment. `env.plugin_host` must be set.
235    /// * `policy` — per-session policy (model, provider, autonomy, turn limits).
236    /// * `state` — persisted session state (empty for a fresh session).
237    /// * `store` — per-session store. `None` builds an embedded runtime
238    ///   with no persistence; `Some` builds a persistent
239    ///   background-capable runtime.
240    pub async fn from_environment(
241        env: &RuntimeEnvironment,
242        policy: SessionPolicy,
243        state: RuntimeSessionState,
244        store: Option<Arc<dyn crate::store::RuntimePersistence>>,
245    ) -> Result<Self, SessionError> {
246        let plugin_host = env.plugin_host.as_ref().ok_or_else(|| {
247            SessionError::Protocol(
248                "RuntimeEnvironment.plugin_host is required for from_environment".to_string(),
249            )
250        })?;
251        let plugin_host = plugin_host.as_ref().clone().with_lashlang_abilities(
252            super::builder::lashlang_abilities_for_process_registry(
253                plugin_host.lashlang_abilities(),
254                env.process_registry.is_some(),
255            ),
256        );
257        let plugin_session = plugin_host
258            .build_session(state.session_id.as_str(), state.plugin_snapshot.as_ref())
259            .map_err(|err| SessionError::Protocol(err.to_string()))?;
260        let mut embedded = EmbeddedRuntimeHost::new(env.core.clone());
261        if let Some(factory) = env.session_store_factory.as_ref() {
262            embedded = embedded.with_session_store_factory(Arc::clone(factory));
263        }
264        let mut runtime = Self::assemble_runtime(
265            policy,
266            embedded,
267            plugin_session,
268            store,
269            env.process_registry.as_ref().cloned(),
270            state,
271            env.residency,
272        )
273        .await?;
274        // Thread the host's process-work poke onto this session's host so the
275        // process control seam can wake the runner after a successful start.
276        runtime.host.process_work_poke = env.process_work_poke.clone();
277        runtime.host.queued_work_poke = env.queued_work_poke.clone();
278        Ok(runtime)
279    }
280
281    /// Persist any dirty state and drop the runtime, returning a lightweight
282    /// handle the embedder can cache and resume later via
283    /// [`LashRuntime::resume`]. This is the webserver-embedder parking
284    /// primitive: the handle holds only the session id, policy, and store
285    /// reference — no graph nodes, no plugin session, no HTTP client.
286    pub async fn park(mut self) -> Result<ParkedSession, SessionError> {
287        let store = self.services.store.clone().ok_or_else(|| {
288            SessionError::Protocol(
289                "park() requires a persistent runtime (store is not set)".to_string(),
290            )
291        })?;
292        let session_id = self.state.session_id.clone();
293        let policy = self.policy.clone();
294        // Flush any dirty resident state to the store before dropping.
295        let commit = crate::store::RuntimeCommit::persisted_state(&self.state, &[]);
296        let result = store.commit_runtime_state(commit).await.map_err(|err| {
297            SessionError::Protocol(format!("failed to persist runtime state: {err}"))
298        })?;
299        self.state.apply_persisted_commit_result(result);
300        // Drain pending tombstones if any. Under KeepHistory this is a
301        // no-op (tombstones never get added). Under DropOrphans,
302        // Phase-9's not-yet-wired rewrite path would have populated the
303        // set — wired fully in Phase 10's vacuum() design.
304        Ok(ParkedSession {
305            session_id,
306            store,
307            policy,
308        })
309    }
310
311    /// Resume a previously parked session against a shared environment.
312    /// Loads only the active-path graph when
313    /// `env.residency == ActivePathOnly`; under `KeepAll`
314    /// loads the full graph (current behavior).
315    pub async fn resume(
316        parked: ParkedSession,
317        env: &RuntimeEnvironment,
318    ) -> Result<Self, SessionError> {
319        // Under ActivePathOnly, skip the full-graph load: fetch head
320        // metadata + the active-path chain only. Durable impls can
321        // ActivePathOnly is an exact store capability. Stores that do
322        // not support it must return UnsupportedReadScope; resume does
323        // not fall back to a full graph load.
324        let loaded = match env.residency {
325            Residency::KeepAll => {
326                crate::store::load_persisted_session_state(parked.store.as_ref()).await
327            }
328            Residency::ActivePathOnly => {
329                crate::store::load_persisted_session_state_active_path(parked.store.as_ref(), None)
330                    .await
331            }
332        }
333        .map_err(|err| SessionError::Protocol(format!("failed to load runtime state: {err}")))?;
334        let state = loaded.unwrap_or_else(|| RuntimeSessionState {
335            session_id: parked.session_id.clone(),
336            policy: parked.policy.clone(),
337            ..RuntimeSessionState::default()
338        });
339        Self::from_environment(env, parked.policy, state, Some(parked.store)).await
340    }
341
342    /// Opt-in async read for historic (non-active-path) nodes under
343    /// `Residency::ActivePathOnly`. Plugins that walk the full graph
344    /// call this instead of `session_graph().find_node()` so missing
345    /// nodes surface as `Ok(None)` rather than silently missing.
346    pub async fn get_historic_node(
347        &self,
348        node_id: &str,
349    ) -> Result<Option<crate::SessionNodeRecord>, SessionError> {
350        if let Some(node) = self.state.session_graph.find_node(node_id) {
351            return Ok(Some(node.clone()));
352        }
353        let store = self.services.store.clone().ok_or_else(|| {
354            SessionError::Protocol("get_historic_node() requires a persistent runtime".to_string())
355        })?;
356        store
357            .load_node(node_id)
358            .await
359            .map_err(|err| SessionError::Protocol(format!("failed to load historic node: {err}")))
360    }
361
362    /// Store-resident node IDs that are NOT reachable from the current
363    /// leaf — i.e. orphans eligible for tombstoning. lash owns RAM; the
364    /// host owns disk lifecycle, so this is a primitive the host calls
365    /// on its own schedule (e.g. every N turns, or off-peak).
366    ///
367    /// Typical autonomous-agent loop:
368    ///
369    /// ```ignore
370    /// let orphans = runtime.orphaned_node_ids().await?;
371    /// if !orphans.is_empty() {
372    ///     store.tombstone_nodes(&orphans).await;
373    /// }
374    /// // And less often:
375    /// store.vacuum().await;
376    /// ```
377    pub async fn orphaned_node_ids(&self) -> Result<Vec<String>, SessionError> {
378        let store = self.services.store.clone().ok_or_else(|| {
379            SessionError::Protocol("orphaned_node_ids() requires a persistent runtime".to_string())
380        })?;
381        let Some(read) = store
382            .load_session(crate::store::SessionReadScope::FullGraph)
383            .await
384            .map_err(|err| SessionError::Protocol(format!("failed to load full graph: {err}")))?
385        else {
386            return Ok(Vec::new());
387        };
388        let active: std::collections::HashSet<&str> = read
389            .graph
390            .active_path_nodes()
391            .iter()
392            .map(|node| node.node_id.as_str())
393            .collect();
394        Ok(read
395            .graph
396            .nodes
397            .iter()
398            .filter(|node| !active.contains(node.node_id.as_str()))
399            .map(|node| node.node_id.clone())
400            .collect())
401    }
402}