Skip to main content

leviath_runtime/
title.rs

1//! One-shot run-title generation.
2//!
3//! The dashboard displays, searches, and persists `RunMetadata.title`; this
4//! module is what fills it in. At spawn, the daemon marks an eligible run
5//! [`PendingTitle`]; [`dispatch_title`] makes one cheap LLM call over the
6//! task prompt via the `title_bridge` worker, and [`collect_title`]
7//! sanitizes the reply into the metadata. Everything downstream (persistence,
8//! dashboard header, run search) already reads the field.
9//!
10//! Best-effort by design: any failure - no usable provider or model, a full
11//! pool that never frees, a provider error, an empty reply - leaves the title
12//! `None` and the run displays its blueprint name exactly as before. The
13//! title lands on disk with the next persistence write (the run-level
14//! heartbeat guarantees one within a few seconds).
15
16use bevy_ecs::prelude::{Commands, Component, Entity, Query, Res, ResMut, Resource, With, Without};
17use leviath_providers::InferenceRequest;
18use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
19
20use crate::persistence::RunMetadata;
21use crate::pipeline::{InferenceStage, Providers};
22use crate::title_bridge::{TitleJob, TitleOutcome, run_title_job};
23
24/// The `[title]` config, as a world resource (inserted by the daemon at
25/// setup). Absent in worlds that never title (tests, `lev run` without it).
26#[derive(Resource, Clone)]
27pub struct TitleSettings(pub leviath_core::config::TitleConfig);
28
29/// This run wants a title; `dispatch_title` picks it up on the next tick.
30/// Inserted at spawn for enabled, root, non-empty-task runs only.
31#[derive(Component, Debug, Clone, Copy)]
32pub struct PendingTitle;
33
34/// A title call is in flight. Unlike `AwaitingCompaction`, this does not hold
35/// the agent out of inference - titling runs alongside the first turn.
36#[derive(Component, Debug, Clone, Copy)]
37pub struct AwaitingTitle;
38
39/// The receiving end of the title-outcomes channel, as a world resource.
40#[derive(Resource)]
41pub struct TitleResults(pub UnboundedReceiver<TitleOutcome>);
42
43/// The sending end, cloned into each spawned title job.
44#[derive(Resource)]
45pub struct TitleSink(pub UnboundedSender<TitleOutcome>);
46
47/// Kept small: a title is one short line, and a runaway reply is cut anyway.
48const TITLE_MAX_TOKENS: usize = 64;
49/// How much of the task prompt the model sees. Titles come from the opening
50/// framing of a task, not its appendix.
51const TITLE_TASK_BUDGET: usize = 2_000;
52/// Display cap, in bytes, cut on a char boundary.
53const TITLE_MAX_LEN: usize = 80;
54
55const TITLE_SYSTEM_PROMPT: &str = "Reply with only a short title for the given task, \
56     at most 8 words. No quotes, no trailing punctuation, no explanation.";
57
58/// Resolve which provider/model the title call should use.
59///
60/// `[title]` config wins where set; unset fields fall back to the run's own
61/// first-stage provider and model (from the `provider/model` label). The one
62/// unguessable case - an explicit title provider that differs from the run's,
63/// with no title model - resolves to `None`, because the run's model name
64/// means nothing to another provider.
65fn resolve_title_model(
66    settings: &leviath_core::config::TitleConfig,
67    run_model_label: Option<&str>,
68) -> Option<(String, String)> {
69    let run = run_model_label.and_then(|label| label.split_once('/'));
70    let provider = settings
71        .provider
72        .clone()
73        .or_else(|| run.map(|(p, _)| p.to_string()))?;
74    let model = settings.model.clone().or_else(|| match run {
75        Some((run_provider, run_model)) if run_provider == provider => Some(run_model.to_string()),
76        _ => None,
77    })?;
78    Some((provider, model))
79}
80
81/// Build the one-shot titling request over the task prompt.
82fn title_request(task: &str, model: &str) -> InferenceRequest {
83    InferenceRequest {
84        system: vec![],
85        messages: vec![
86            leviath_providers::Message {
87                role: "system".to_string(),
88                content: TITLE_SYSTEM_PROMPT.to_string().into(),
89                cache_breakpoint: false,
90            },
91            leviath_providers::Message {
92                role: "user".to_string(),
93                content: leviath_core::truncate_at_boundary(task, TITLE_TASK_BUDGET)
94                    .to_string()
95                    .into(),
96                cache_breakpoint: false,
97            },
98        ],
99        model: model.to_string(),
100        max_tokens: TITLE_MAX_TOKENS,
101        temperature: 0.2,
102        tools: Vec::new(),
103        extra: serde_json::Value::Null,
104        request_timeout_secs: None,
105    }
106}
107
108/// Reduce a raw model reply to a displayable one-line title: the first
109/// non-empty line, unquoted, capped at [`TITLE_MAX_LEN`]. Empty means "no
110/// title" and the metadata stays untouched.
111fn sanitize_title(raw: &str) -> String {
112    let first = raw
113        .lines()
114        .map(str::trim)
115        .find(|l| !l.is_empty())
116        .unwrap_or("");
117    let unquoted = first.trim_matches(['"', '\'', '`']).trim();
118    leviath_core::truncate_at_boundary(unquoted, TITLE_MAX_LEN)
119        .trim_end()
120        .to_string()
121}
122
123/// Dispatch system: start the title call for each [`PendingTitle`] run.
124///
125/// A full pool leaves the marker in place to retry next tick; every other
126/// dead end (no settings resource, no resolvable provider/model, provider
127/// not registered) drops the marker so the query empties instead of spinning.
128#[allow(clippy::type_complexity)]
129pub fn dispatch_title(
130    agents: Query<(Entity, &RunMetadata), (With<PendingTitle>, Without<AwaitingTitle>)>,
131    settings: Option<Res<TitleSettings>>,
132    stage: Res<InferenceStage>,
133    providers: Res<Providers>,
134    sink: Res<TitleSink>,
135    mut commands: Commands,
136) {
137    crate::tick_scope::clear();
138    for (entity, meta) in agents.iter() {
139        crate::tick_scope::enter(entity);
140        let resolved = settings
141            .as_ref()
142            .filter(|s| s.0.enabled)
143            .and_then(|s| resolve_title_model(&s.0, meta.model.as_deref()));
144        let Some((provider_name, model)) = resolved else {
145            tracing::debug!(run_id = %meta.run_id, "no usable title provider/model; skipping");
146            commands.entity(entity).remove::<PendingTitle>();
147            continue;
148        };
149        let Some(provider) = providers.0.get(&provider_name) else {
150            tracing::debug!(
151                run_id = %meta.run_id,
152                provider = %provider_name,
153                "title provider not registered; skipping"
154            );
155            commands.entity(entity).remove::<PendingTitle>();
156            continue;
157        };
158        let Some(permit) = stage.pools.try_acquire(&model) else {
159            continue; // pool full - retry next tick
160        };
161
162        stage.runtime.spawn(run_title_job(
163            TitleJob {
164                entity,
165                provider,
166                request: title_request(&meta.task, &model),
167                permit,
168            },
169            std::time::Duration::from_secs(leviath_providers::DEFAULT_INFERENCE_TIMEOUT_SECS),
170            sink.0.clone(),
171            stage.wake.clone(),
172        ));
173        commands
174            .entity(entity)
175            .remove::<PendingTitle>()
176            .insert(AwaitingTitle);
177    }
178}
179
180/// Collect system: store each finished title into its run's metadata. A
181/// provider error or empty reply changes nothing; either way the in-flight
182/// marker comes off.
183pub fn collect_title(
184    mut results: ResMut<TitleResults>,
185    mut agents: Query<&mut RunMetadata, With<AwaitingTitle>>,
186    mut commands: Commands,
187) {
188    crate::tick_scope::clear();
189    while let Ok(outcome) = results.0.try_recv() {
190        let Ok(mut meta) = agents.get_mut(outcome.entity) else {
191            continue; // stale: agent cancelled/despawned since dispatch
192        };
193        crate::tick_scope::enter(outcome.entity);
194        if let Ok(raw) = outcome.result {
195            let title = sanitize_title(&raw);
196            if !title.is_empty() {
197                meta.title = Some(title);
198            }
199        }
200        commands.entity(outcome.entity).remove::<AwaitingTitle>();
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use bevy_ecs::schedule::Schedule;
208    use bevy_ecs::world::World;
209    use leviath_providers::{Provider, ProviderError};
210    use std::sync::Arc;
211    use tokio::runtime::Handle;
212    use tokio::sync::Notify;
213    use tokio::sync::mpsc;
214
215    /// A provider whose single call yields a fixed reply or a fixed error.
216    struct Scripted(Result<&'static str, &'static str>);
217
218    #[async_trait::async_trait]
219    impl Provider for Scripted {
220        async fn infer(
221            &self,
222            _r: InferenceRequest,
223        ) -> leviath_providers::Result<leviath_providers::InferenceResponse> {
224            match self.0 {
225                Ok(reply) => Ok(leviath_providers::InferenceResponse {
226                    content: reply.to_string(),
227                    tool_calls: vec![],
228                    tokens_used: leviath_providers::TokenUsage {
229                        prompt_tokens: 1,
230                        completion_tokens: 1,
231                        total_tokens: 2,
232                        cached_tokens: 0,
233                        cache_write_tokens: 0,
234                    },
235                    finish_reason: leviath_providers::FinishReason::Complete,
236                }),
237                Err(msg) => Err(ProviderError::Other(msg.to_string())),
238            }
239        }
240        async fn count_tokens(&self, _t: &str, _m: &str) -> usize {
241            1
242        }
243        fn max_context_tokens(&self, _m: &str) -> usize {
244            100_000
245        }
246        fn name(&self) -> &str {
247            "mock"
248        }
249        fn capabilities(&self, _m: &str) -> leviath_providers::ModelCapabilities {
250            leviath_providers::ModelCapabilities::default()
251        }
252    }
253
254    fn metadata(model: Option<&str>) -> RunMetadata {
255        RunMetadata {
256            run_id: "run-t".to_string(),
257            agent_name: "titled".to_string(),
258            agent_path: "/a".to_string(),
259            task: "summarize the release notes".to_string(),
260            model: model.map(str::to_string),
261            workdir: "/w".to_string(),
262            num_stages: 1,
263            started_at: 0,
264            parent_run_id: None,
265            metadata: Default::default(),
266            callback_url: None,
267            callback_secret: None,
268            title: None,
269        }
270    }
271
272    /// A world with the title lane wired over the given provider outcome, plus
273    /// the receiver the dispatched job reports into.
274    fn build_world(
275        reply: Result<&'static str, &'static str>,
276        pools: crate::inference_pool::InferencePools,
277    ) -> (World, mpsc::UnboundedReceiver<TitleOutcome>) {
278        let mut registry = crate::ProviderRegistry::new();
279        registry.register("mock".to_string(), Arc::new(Scripted(reply)));
280        let (title_tx, title_rx) = mpsc::unbounded_channel();
281        let (inf_tx, _inf_rx) = mpsc::unbounded_channel();
282        let (ttx, _trx) = mpsc::unbounded_channel();
283        let (ctx, _crx) = mpsc::unbounded_channel();
284        let (cstx, _csrx) = mpsc::unbounded_channel();
285        let mut world = World::new();
286        world.insert_resource(Providers(registry));
287        world.insert_resource(InferenceStage {
288            pools: Arc::new(pools),
289            outcomes: inf_tx,
290            transition_outcomes: ttx,
291            compaction_outcomes: ctx,
292            content_summary_outcomes: cstx,
293            wake: Arc::new(Notify::new()),
294            runtime: Handle::current(),
295            exact_token_counting: false,
296        });
297        world.insert_resource(TitleSink(title_tx));
298        (world, title_rx)
299    }
300
301    fn run_dispatch(world: &mut World) {
302        let mut schedule = Schedule::default();
303        schedule.add_systems(dispatch_title);
304        schedule.run(world);
305    }
306
307    fn run_collect(world: &mut World) {
308        let mut schedule = Schedule::default();
309        schedule.add_systems(collect_title);
310        schedule.run(world);
311    }
312
313    fn default_pools() -> crate::inference_pool::InferencePools {
314        crate::inference_pool::InferencePools::new(crate::inference_pool::InferencePoolConfig::new())
315    }
316
317    /// The permit must come back within the deadline even when the provider
318    /// never answers - a hung title call once held its pool slot forever.
319    #[tokio::test]
320    async fn title_deadline_frees_the_slot_when_the_provider_hangs() {
321        struct Hang;
322        #[async_trait::async_trait]
323        impl Provider for Hang {
324            async fn infer(
325                &self,
326                _r: InferenceRequest,
327            ) -> leviath_providers::Result<leviath_providers::InferenceResponse> {
328                std::future::pending().await
329            }
330            async fn count_tokens(&self, _t: &str, _m: &str) -> usize {
331                1
332            }
333            fn max_context_tokens(&self, _m: &str) -> usize {
334                100_000
335            }
336            fn name(&self) -> &str {
337                "hang"
338            }
339            fn capabilities(&self, _m: &str) -> leviath_providers::ModelCapabilities {
340                leviath_providers::ModelCapabilities::default()
341            }
342        }
343
344        // Trait obligations on the mock; only `infer` matters to this test.
345        assert_eq!(Hang.count_tokens("t", "m").await, 1);
346        assert_eq!(Hang.max_context_tokens("m"), 100_000);
347        assert_eq!(Hang.name(), "hang");
348        let _ = Hang.capabilities("m");
349        let pools = crate::inference_pool::InferencePools::new(
350            crate::inference_pool::InferencePoolConfig::new(),
351        );
352        let (tx, mut rx) = mpsc::unbounded_channel();
353        run_title_job(
354            TitleJob {
355                entity: bevy_ecs::entity::Entity::PLACEHOLDER,
356                provider: Arc::new(Hang),
357                request: title_request("task", "m"),
358                permit: pools.try_acquire("m").expect("free"),
359            },
360            std::time::Duration::from_millis(5),
361            tx,
362            Arc::new(Notify::new()),
363        )
364        .await;
365        let outcome = rx.recv().await.expect("an outcome is always reported");
366        let err = outcome.result.expect_err("the deadline must surface");
367        assert!(err.to_string().contains("deadline"), "{err}");
368    }
369
370    #[tokio::test]
371    async fn dispatch_and_collect_set_the_title() {
372        let (mut world, title_rx) = build_world(Ok("\"Release notes digest\"\n"), default_pools());
373        world.insert_resource(TitleSettings(config(None, None)));
374        let e = world.spawn((metadata(Some("mock/m")), PendingTitle)).id();
375
376        run_dispatch(&mut world);
377        assert!(world.get::<PendingTitle>(e).is_none());
378        assert!(world.get::<AwaitingTitle>(e).is_some());
379
380        // Await the spawned job's report, then hand it to the collector
381        // through the results resource.
382        let mut title_rx = title_rx;
383        let outcome = title_rx.recv().await.expect("job reported");
384        assert_eq!(outcome.entity, e);
385        let (tx, rx) = mpsc::unbounded_channel();
386        tx.send(outcome).unwrap();
387        world.insert_resource(TitleResults(rx));
388
389        run_collect(&mut world);
390        assert_eq!(
391            world.get::<RunMetadata>(e).unwrap().title.as_deref(),
392            Some("Release notes digest")
393        );
394        assert!(world.get::<AwaitingTitle>(e).is_none());
395    }
396
397    #[tokio::test]
398    async fn provider_error_leaves_the_title_unset() {
399        let (mut world, mut title_rx) = build_world(Err("boom"), default_pools());
400        world.insert_resource(TitleSettings(config(None, None)));
401        let e = world.spawn((metadata(Some("mock/m")), PendingTitle)).id();
402
403        run_dispatch(&mut world);
404        let outcome = title_rx.recv().await.expect("job reported");
405        assert!(outcome.result.is_err());
406        let (tx, rx) = mpsc::unbounded_channel();
407        tx.send(outcome).unwrap();
408        world.insert_resource(TitleResults(rx));
409
410        run_collect(&mut world);
411        assert_eq!(world.get::<RunMetadata>(e).unwrap().title, None);
412        assert!(world.get::<AwaitingTitle>(e).is_none());
413    }
414
415    #[tokio::test]
416    async fn whitespace_reply_leaves_the_title_unset() {
417        let (mut world, mut title_rx) = build_world(Ok("  \n \n"), default_pools());
418        world.insert_resource(TitleSettings(config(None, None)));
419        let e = world.spawn((metadata(Some("mock/m")), PendingTitle)).id();
420
421        run_dispatch(&mut world);
422        let outcome = title_rx.recv().await.expect("job reported");
423        let (tx, rx) = mpsc::unbounded_channel();
424        tx.send(outcome).unwrap();
425        world.insert_resource(TitleResults(rx));
426
427        run_collect(&mut world);
428        assert_eq!(world.get::<RunMetadata>(e).unwrap().title, None);
429    }
430
431    #[tokio::test]
432    async fn collect_skips_a_despawned_agent() {
433        let (mut world, _title_rx) = build_world(Ok("t"), default_pools());
434        let (tx, rx) = mpsc::unbounded_channel();
435        // A ghost entity id: spawn then despawn.
436        let ghost = world.spawn(metadata(Some("mock/m"))).id();
437        world.despawn(ghost);
438        tx.send(TitleOutcome {
439            entity: ghost,
440            result: Ok("t".to_string()),
441        })
442        .unwrap();
443        world.insert_resource(TitleResults(rx));
444        run_collect(&mut world); // must not panic
445    }
446
447    #[tokio::test]
448    async fn dispatch_without_settings_drops_the_marker() {
449        let (mut world, _title_rx) = build_world(Ok("t"), default_pools());
450        let e = world.spawn((metadata(Some("mock/m")), PendingTitle)).id();
451        run_dispatch(&mut world);
452        assert!(world.get::<PendingTitle>(e).is_none());
453        assert!(world.get::<AwaitingTitle>(e).is_none());
454    }
455
456    #[tokio::test]
457    async fn dispatch_with_disabled_settings_drops_the_marker() {
458        let (mut world, _title_rx) = build_world(Ok("t"), default_pools());
459        world.insert_resource(TitleSettings(leviath_core::config::TitleConfig {
460            enabled: false,
461            provider: None,
462            model: None,
463        }));
464        let e = world.spawn((metadata(Some("mock/m")), PendingTitle)).id();
465        run_dispatch(&mut world);
466        assert!(world.get::<PendingTitle>(e).is_none());
467        assert!(world.get::<AwaitingTitle>(e).is_none());
468    }
469
470    #[tokio::test]
471    async fn dispatch_with_unregistered_provider_drops_the_marker() {
472        let (mut world, _title_rx) = build_world(Ok("t"), default_pools());
473        world.insert_resource(TitleSettings(config(Some("nowhere"), Some("m"))));
474        let e = world.spawn((metadata(Some("mock/m")), PendingTitle)).id();
475        run_dispatch(&mut world);
476        assert!(world.get::<PendingTitle>(e).is_none());
477        assert!(world.get::<AwaitingTitle>(e).is_none());
478    }
479
480    #[tokio::test]
481    async fn dispatch_retries_while_the_pool_is_full() {
482        let mut cfg = crate::inference_pool::InferencePoolConfig::new();
483        cfg.set_limit("m", 1);
484        let pools = crate::inference_pool::InferencePools::new(cfg);
485        let held = pools.try_acquire("m").unwrap();
486        let (mut world, _title_rx) = build_world(Ok("t"), pools);
487        world.insert_resource(TitleSettings(config(None, None)));
488        let e = world.spawn((metadata(Some("mock/m")), PendingTitle)).id();
489
490        run_dispatch(&mut world);
491        // Slot occupied: the marker stays so the next tick retries.
492        assert!(world.get::<PendingTitle>(e).is_some());
493        assert!(world.get::<AwaitingTitle>(e).is_none());
494        drop(held);
495    }
496
497    fn config(provider: Option<&str>, model: Option<&str>) -> leviath_core::config::TitleConfig {
498        leviath_core::config::TitleConfig {
499            enabled: true,
500            provider: provider.map(str::to_string),
501            model: model.map(str::to_string),
502        }
503    }
504
505    #[test]
506    fn resolve_prefers_the_configured_pair() {
507        assert_eq!(
508            resolve_title_model(
509                &config(Some("openai"), Some("gpt-5-mini")),
510                Some("anthropic/m")
511            ),
512            Some(("openai".to_string(), "gpt-5-mini".to_string()))
513        );
514    }
515
516    #[test]
517    fn resolve_falls_back_to_the_runs_provider_and_model() {
518        assert_eq!(
519            resolve_title_model(&config(None, None), Some("anthropic/claude-x")),
520            Some(("anthropic".to_string(), "claude-x".to_string()))
521        );
522    }
523
524    #[test]
525    fn resolve_borrows_the_runs_model_only_for_the_same_provider() {
526        assert_eq!(
527            resolve_title_model(&config(Some("anthropic"), None), Some("anthropic/claude-x")),
528            Some(("anthropic".to_string(), "claude-x".to_string()))
529        );
530        // A different provider cannot use the run's model name.
531        assert_eq!(
532            resolve_title_model(&config(Some("openai"), None), Some("anthropic/claude-x")),
533            None
534        );
535    }
536
537    #[test]
538    fn resolve_gives_up_without_any_provider_or_model() {
539        assert_eq!(resolve_title_model(&config(None, None), None), None);
540        assert_eq!(resolve_title_model(&config(None, Some("m")), None), None);
541        // A label without a slash carries no provider/model split.
542        assert_eq!(
543            resolve_title_model(&config(None, None), Some("bare-label")),
544            None
545        );
546    }
547
548    #[test]
549    fn title_request_truncates_the_task_and_carries_the_model() {
550        let long_task = "x".repeat(5_000);
551        let req = title_request(&long_task, "gpt-5-mini");
552        assert_eq!(req.model, "gpt-5-mini");
553        assert_eq!(req.max_tokens, TITLE_MAX_TOKENS);
554        assert_eq!(req.messages.len(), 2);
555        let expected: leviath_providers::MessageContent =
556            leviath_core::truncate_at_boundary(&long_task, TITLE_TASK_BUDGET)
557                .to_string()
558                .into();
559        assert_eq!(req.messages[1].content, expected);
560    }
561
562    #[tokio::test]
563    async fn scripted_provider_metadata_is_exercised() {
564        // Keep the mock's non-`infer` trait methods measured.
565        let p = Scripted(Ok("t"));
566        assert_eq!(p.name(), "mock");
567        assert_eq!(p.count_tokens("t", "m").await, 1);
568        assert_eq!(p.max_context_tokens("m"), 100_000);
569        let default = leviath_providers::ModelCapabilities::default();
570        assert_eq!(
571            p.capabilities("m").max_output_tokens,
572            default.max_output_tokens
573        );
574    }
575
576    #[test]
577    fn sanitize_takes_the_first_line_unquoted_and_capped() {
578        assert_eq!(
579            sanitize_title("\"Fix the login bug\"\nextra"),
580            "Fix the login bug"
581        );
582        assert_eq!(
583            sanitize_title("\n\n  'Tidy: workspace'  \n"),
584            "Tidy: workspace"
585        );
586        assert_eq!(sanitize_title("   \n\t\n"), "");
587        let long = "word ".repeat(40);
588        assert!(sanitize_title(&long).len() <= TITLE_MAX_LEN);
589    }
590}