Skip to main content

codewhale_core/
lib.rs

1pub mod fragments;
2pub mod ids;
3pub mod journal;
4pub mod request;
5pub mod role;
6pub mod session;
7pub mod tool_parser;
8
9use std::collections::{HashMap, HashSet};
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12
13use std::time::Duration;
14
15use anyhow::{Result, anyhow};
16use codewhale_agent::ModelRegistry;
17use codewhale_config::{ConfigToml, ProviderKind};
18use codewhale_execpolicy::{
19    AskForApproval, ExecApprovalRequirement, ExecPolicyContext, ExecPolicyDecision,
20    ExecPolicyEngine,
21};
22use codewhale_hooks::{HookDispatcher, HookEvent};
23use codewhale_mcp::{
24    McpManager, McpStartupCompleteEvent, McpStartupStatus as McpManagerStartupStatus,
25};
26use codewhale_protocol::{
27    AppResponse, EventFrame, ExecApprovalRequestEvent, ResponseChannel, ReviewDecision, Status,
28    Thread, ThreadForkParams, ThreadGoal, ThreadGoalClearParams, ThreadGoalGetParams,
29    ThreadGoalProgressParams, ThreadGoalSetParams, ThreadGoalStatus, ThreadListParams,
30    ThreadReadParams, ThreadRequest, ThreadResponse, ThreadResumeParams, ThreadSetNameParams,
31    ThreadStatus, ToolPayload, UserInputRequestEvent,
32};
33use codewhale_state::{
34    JobStateRecord, JobStateStatus, SessionSource, StateStore, ThreadGoalRecord,
35    ThreadGoalStatus as PersistedThreadGoalStatus, ThreadListFilters, ThreadMetadata,
36    ThreadStatus as PersistedThreadStatus,
37};
38use codewhale_tools::{ToolCall, ToolRegistry};
39use serde_json::{Value, json};
40use tokio::time;
41use uuid::Uuid;
42
43/// Per-tool dispatch budget for the headless runtime. Matches the generous
44/// subagent default so long-running tools are not cut off prematurely.
45fn tool_dispatch_timeout() -> Duration {
46    if cfg!(test) {
47        Duration::from_millis(50)
48    } else {
49        Duration::from_secs(300)
50    }
51}
52
53/// How a new thread's conversation history is initialized.
54#[derive(Debug, Clone)]
55pub enum InitialHistory {
56    /// Start with an empty conversation.
57    New,
58    /// Forked from an existing thread with the given history items.
59    Forked(Vec<Value>),
60    /// Resumed from a persisted thread with its full history.
61    Resumed {
62        conversation_id: String,
63        history: Vec<Value>,
64        rollout_path: PathBuf,
65    },
66}
67
68/// Result of spawning or resuming a thread.
69#[derive(Debug, Clone)]
70pub struct NewThread {
71    /// The thread metadata.
72    pub thread: Thread,
73    /// Resolved model identifier.
74    pub model: String,
75    /// Provider that serves the model.
76    pub model_provider: String,
77    /// Working directory for the thread.
78    pub cwd: PathBuf,
79    /// Approval policy override, if any.
80    pub approval_policy: Option<String>,
81    /// Sandbox mode override, if any.
82    pub sandbox: Option<String>,
83}
84
85/// Status of a background job.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum JobStatus {
88    /// Waiting to be picked up.
89    Queued,
90    /// Currently executing.
91    Running,
92    /// Temporarily paused.
93    Paused,
94    /// Finished successfully.
95    Completed,
96    /// Finished with an error.
97    Failed,
98    /// Cancelled by the user.
99    Cancelled,
100}
101
102impl Status for JobStatus {
103    fn is_terminal(&self) -> bool {
104        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
105    }
106    fn is_active(&self) -> bool {
107        matches!(self, Self::Queued | Self::Running)
108    }
109    fn is_paused(&self) -> bool {
110        matches!(self, Self::Paused)
111    }
112}
113
114const JOB_DETAIL_SCHEMA_VERSION: u8 = 1;
115const DEFAULT_JOB_MAX_ATTEMPTS: u32 = 3;
116const DEFAULT_JOB_BACKOFF_BASE_MS: u64 = 500;
117const MAX_JOB_HISTORY_ENTRIES: usize = 64;
118
119/// Retry state for a job that failed and may be retried.
120#[derive(Debug, Clone)]
121pub struct JobRetryMetadata {
122    /// Current attempt number (0 = not yet retried).
123    pub attempt: u32,
124    /// Maximum number of retry attempts before giving up.
125    pub max_attempts: u32,
126    /// Base delay in milliseconds for exponential backoff.
127    pub backoff_base_ms: u64,
128    /// Computed delay in milliseconds until the next retry.
129    pub next_backoff_ms: u64,
130    /// Timestamp when the next retry should be attempted.
131    pub next_retry_at: Option<i64>,
132}
133
134impl Default for JobRetryMetadata {
135    fn default() -> Self {
136        Self {
137            attempt: 0,
138            max_attempts: DEFAULT_JOB_MAX_ATTEMPTS,
139            backoff_base_ms: DEFAULT_JOB_BACKOFF_BASE_MS,
140            next_backoff_ms: 0,
141            next_retry_at: None,
142        }
143    }
144}
145
146/// A single entry in a job's history log.
147#[derive(Debug, Clone)]
148pub struct JobHistoryEntry {
149    /// Timestamp when this entry was recorded.
150    pub at: i64,
151    /// Phase name (e.g., "created", "running", "failed").
152    pub phase: String,
153    /// Job status at this point in time.
154    pub status: JobStatus,
155    /// Progress percentage at this point, if available.
156    pub progress: Option<u8>,
157    /// Human-readable detail message.
158    pub detail: Option<String>,
159    /// Retry state snapshot at this point.
160    pub retry: JobRetryMetadata,
161}
162
163#[derive(Debug, Clone)]
164struct PersistedJobDetail {
165    pub status: JobStatus,
166    pub detail: Option<String>,
167    pub retry: JobRetryMetadata,
168    pub history: Vec<JobHistoryEntry>,
169}
170
171/// A complete job record with all metadata and history.
172#[derive(Debug, Clone)]
173pub struct JobRecord {
174    /// Unique job identifier.
175    pub id: String,
176    /// Human-readable job name.
177    pub name: String,
178    /// Current job status.
179    pub status: JobStatus,
180    /// Current progress percentage (0-100).
181    pub progress: Option<u8>,
182    /// Human-readable detail about the current state.
183    pub detail: Option<String>,
184    /// Retry state for failed jobs.
185    pub retry: JobRetryMetadata,
186    /// Chronological history of state transitions.
187    pub history: Vec<JobHistoryEntry>,
188    /// Timestamp when the job was created.
189    pub created_at: i64,
190    /// Timestamp of the last state change.
191    pub updated_at: i64,
192}
193
194/// Map a durable [`JobRecord`] to the dependency-neutral run read model.
195///
196/// Pure projection of the record as persisted: unknown budgets stay unset and
197/// nothing is fabricated. `updated_at` (epoch seconds) provides the terminal
198/// timestamp because the job manager records no separate end time. The
199/// free-form job detail is intentionally omitted because this owner does not
200/// classify it as safe for a cross-surface read model.
201#[must_use]
202pub fn job_record_to_agent_run(
203    record: &JobRecord,
204) -> codewhale_protocol::agent_run::AgentRunSnapshot {
205    use codewhale_protocol::agent_run::{
206        AgentRunSnapshot, BudgetSummary, RunSource, RunState, TerminalOutcome, TerminalSummary,
207    };
208
209    let (state, terminal) = match record.status {
210        JobStatus::Queued => (RunState::Queued, None),
211        JobStatus::Running => (RunState::Running, None),
212        JobStatus::Paused => (RunState::Paused, None),
213        JobStatus::Completed | JobStatus::Failed | JobStatus::Cancelled => {
214            let outcome = match record.status {
215                JobStatus::Completed => TerminalOutcome::Completed,
216                JobStatus::Failed => TerminalOutcome::Failed,
217                _ => TerminalOutcome::Cancelled,
218            };
219            (
220                RunState::Terminal,
221                Some(TerminalSummary {
222                    outcome,
223                    ended_at_ms: record.updated_at.checked_mul(1000),
224                    detail: None,
225                }),
226            )
227        }
228    };
229
230    AgentRunSnapshot {
231        run_id: record.id.clone(),
232        parent: None,
233        source: RunSource::CoreJob,
234        state,
235        budget: BudgetSummary::default(),
236        terminal,
237        refs: Vec::new(),
238    }
239}
240
241/// Manages background jobs with retry logic and persistence.
242#[derive(Debug, Default)]
243pub struct JobManager {
244    jobs: HashMap<String, JobRecord>,
245}
246
247impl JobManager {
248    fn now_ts() -> i64 {
249        chrono::Utc::now().timestamp()
250    }
251
252    fn deterministic_backoff_ms(retry: &JobRetryMetadata) -> u64 {
253        if retry.attempt == 0 {
254            return 0;
255        }
256        let exponent = retry.attempt.saturating_sub(1).min(20);
257        let multiplier = 1u64.checked_shl(exponent).unwrap_or(u64::MAX);
258        retry.backoff_base_ms.saturating_mul(multiplier)
259    }
260
261    fn clear_retry_schedule(retry: &mut JobRetryMetadata) {
262        retry.next_backoff_ms = 0;
263        retry.next_retry_at = None;
264    }
265
266    fn push_history(job: &mut JobRecord, phase: &str) {
267        job.history.push(JobHistoryEntry {
268            at: job.updated_at,
269            phase: phase.to_string(),
270            status: job.status,
271            progress: job.progress,
272            detail: job.detail.clone(),
273            retry: job.retry.clone(),
274        });
275        if job.history.len() > MAX_JOB_HISTORY_ENTRIES {
276            let to_drain = job.history.len() - MAX_JOB_HISTORY_ENTRIES;
277            job.history.drain(0..to_drain);
278        }
279    }
280
281    fn parse_persisted_detail(raw: Option<&str>) -> Option<PersistedJobDetail> {
282        let raw = raw?;
283        let parsed: Value = serde_json::from_str(raw).ok()?;
284        let status = parsed
285            .get("status")
286            .and_then(Value::as_str)
287            .and_then(job_status_from_str)?;
288        let detail = parsed.get("detail").and_then(json_optional_string);
289        let retry = parse_retry_metadata(parsed.get("retry"));
290        let history = parsed
291            .get("history")
292            .and_then(Value::as_array)
293            .map(|items| {
294                items
295                    .iter()
296                    .filter_map(parse_history_entry)
297                    .collect::<Vec<_>>()
298            })
299            .unwrap_or_default();
300        Some(PersistedJobDetail {
301            status,
302            detail,
303            retry,
304            history,
305        })
306    }
307
308    fn encode_persisted_detail(job: &JobRecord) -> Result<Option<String>> {
309        let encoded = json!({
310            "schema_version": JOB_DETAIL_SCHEMA_VERSION,
311            "status": job_status_to_str(job.status),
312            "detail": job.detail.clone(),
313            "retry": job_retry_to_value(&job.retry),
314            "history": job.history.iter().map(job_history_to_value).collect::<Vec<_>>()
315        })
316        .to_string();
317        Ok(Some(encoded))
318    }
319
320    /// Enqueues a new job and returns its record.
321    pub fn enqueue(&mut self, name: impl Into<String>) -> JobRecord {
322        let now = Self::now_ts();
323        let id = format!("job-{}", Uuid::new_v4());
324        let mut job = JobRecord {
325            id: id.clone(),
326            name: name.into(),
327            status: JobStatus::Queued,
328            progress: Some(0),
329            detail: None,
330            retry: JobRetryMetadata::default(),
331            history: Vec::new(),
332            created_at: now,
333            updated_at: now,
334        };
335        Self::push_history(&mut job, "created");
336        self.jobs.insert(id, job.clone());
337        job
338    }
339
340    /// Transitions a job to running and clears its retry schedule.
341    pub fn set_running(&mut self, id: &str) {
342        if let Some(job) = self.jobs.get_mut(id) {
343            job.status = JobStatus::Running;
344            Self::clear_retry_schedule(&mut job.retry);
345            job.updated_at = Self::now_ts();
346            Self::push_history(job, "running");
347        }
348    }
349
350    /// Updates a job's progress (clamped to 100) and optional detail message.
351    pub fn update_progress(&mut self, id: &str, progress: u8, detail: Option<String>) {
352        if let Some(job) = self.jobs.get_mut(id) {
353            job.progress = Some(progress.min(100));
354            job.detail = detail;
355            job.updated_at = Self::now_ts();
356            Self::push_history(job, "progress_updated");
357        }
358    }
359
360    /// Marks a job as completed with 100% progress and clears its retry schedule.
361    pub fn complete(&mut self, id: &str) {
362        if let Some(job) = self.jobs.get_mut(id) {
363            job.status = JobStatus::Completed;
364            job.progress = Some(100);
365            Self::clear_retry_schedule(&mut job.retry);
366            job.updated_at = Self::now_ts();
367            Self::push_history(job, "completed");
368        }
369    }
370
371    /// Marks a job as failed and schedules a retry if attempts remain.
372    pub fn fail(&mut self, id: &str, detail: impl Into<String>) {
373        if let Some(job) = self.jobs.get_mut(id) {
374            let now = Self::now_ts();
375            job.status = JobStatus::Failed;
376            job.detail = Some(detail.into());
377            if job.retry.attempt < job.retry.max_attempts {
378                job.retry.attempt += 1;
379                job.retry.next_backoff_ms = Self::deterministic_backoff_ms(&job.retry);
380                let delay_secs = ((job.retry.next_backoff_ms.saturating_add(999)) / 1000)
381                    .min(i64::MAX as u64) as i64;
382                job.retry.next_retry_at = Some(now.saturating_add(delay_secs));
383            } else {
384                Self::clear_retry_schedule(&mut job.retry);
385            }
386            job.updated_at = now;
387            Self::push_history(job, "failed");
388        }
389    }
390
391    /// Cancels a job and clears any pending retry schedule.
392    pub fn cancel(&mut self, id: &str) {
393        if let Some(job) = self.jobs.get_mut(id) {
394            job.status = JobStatus::Cancelled;
395            Self::clear_retry_schedule(&mut job.retry);
396            job.updated_at = Self::now_ts();
397            Self::push_history(job, "cancelled");
398        }
399    }
400
401    /// Pauses a job, optionally updating its detail message.
402    pub fn pause(&mut self, id: &str, detail: Option<String>) {
403        if let Some(job) = self.jobs.get_mut(id) {
404            job.status = JobStatus::Paused;
405            if detail.is_some() {
406                job.detail = detail;
407            }
408            job.updated_at = Self::now_ts();
409            Self::push_history(job, "paused");
410        }
411    }
412
413    /// Resumes a paused or failed job back to running status.
414    pub fn resume(&mut self, id: &str, detail: Option<String>) {
415        if let Some(job) = self.jobs.get_mut(id) {
416            job.status = JobStatus::Running;
417            if detail.is_some() {
418                job.detail = detail;
419            }
420            Self::clear_retry_schedule(&mut job.retry);
421            job.updated_at = Self::now_ts();
422            Self::push_history(job, "resumed");
423        }
424    }
425
426    /// Returns all jobs sorted by most recently updated first.
427    pub fn list(&self) -> Vec<JobRecord> {
428        let mut out = self.jobs.values().cloned().collect::<Vec<_>>();
429        out.sort_by_key(|job| std::cmp::Reverse(job.updated_at));
430        out
431    }
432
433    /// Returns the history entries for a job, or an empty vec if not found.
434    pub fn history(&self, id: &str) -> Vec<JobHistoryEntry> {
435        self.jobs
436            .get(id)
437            .map(|job| job.history.clone())
438            .unwrap_or_default()
439    }
440
441    /// Resets queued or running jobs back to queued on application resume.
442    pub fn resume_pending(&mut self) -> Vec<JobRecord> {
443        let mut resumed = Vec::new();
444        for job in self.jobs.values_mut() {
445            if matches!(job.status, JobStatus::Queued | JobStatus::Running) {
446                job.status = JobStatus::Queued;
447                job.updated_at = Self::now_ts();
448                Self::push_history(job, "queued_after_resume");
449                resumed.push(job.clone());
450            }
451        }
452        resumed
453    }
454
455    /// Loads jobs from the state store, deserializing extended detail when available.
456    pub fn load_from_store(&mut self, store: &StateStore) -> Result<()> {
457        let persisted = store.list_jobs(Some(500))?;
458        for job in persisted {
459            let fallback_status = job_state_status_to_runtime(job.status);
460            let parsed = Self::parse_persisted_detail(job.detail.as_deref());
461            let (status, detail, retry, history) = if let Some(detail_state) = parsed {
462                (
463                    detail_state.status,
464                    detail_state.detail,
465                    detail_state.retry,
466                    detail_state.history,
467                )
468            } else {
469                (
470                    fallback_status,
471                    job.detail,
472                    JobRetryMetadata::default(),
473                    Vec::new(),
474                )
475            };
476            self.jobs.insert(
477                job.id.clone(),
478                JobRecord {
479                    id: job.id,
480                    name: job.name,
481                    status,
482                    progress: job.progress,
483                    detail,
484                    retry,
485                    history,
486                    created_at: job.created_at,
487                    updated_at: job.updated_at,
488                },
489            );
490        }
491        Ok(())
492    }
493
494    /// Persists a single job's current state to the state store.
495    pub fn persist_job(&self, store: &StateStore, id: &str) -> Result<()> {
496        let Some(job) = self.jobs.get(id) else {
497            return Ok(());
498        };
499        let encoded_detail = Self::encode_persisted_detail(job)?;
500        store.upsert_job(&JobStateRecord {
501            id: job.id.clone(),
502            name: job.name.clone(),
503            status: runtime_status_to_job_state(job.status),
504            progress: job.progress,
505            detail: encoded_detail,
506            created_at: job.created_at,
507            updated_at: job.updated_at,
508        })
509    }
510
511    /// Persists all in-memory jobs to the state store.
512    pub fn persist_all(&self, store: &StateStore) -> Result<()> {
513        for id in self.jobs.keys() {
514            self.persist_job(store, id)?;
515        }
516        Ok(())
517    }
518}
519
520/// Manages thread lifecycle: spawn, resume, fork, archive, and persistence.
521pub struct ThreadManager {
522    store: StateStore,
523    running_threads: HashMap<String, Thread>,
524    cli_version: String,
525}
526
527impl ThreadManager {
528    /// Creates a new `ThreadManager` backed by the given state store.
529    pub fn new(store: StateStore) -> Self {
530        Self {
531            store,
532            running_threads: HashMap::new(),
533            cli_version: env!("CARGO_PKG_VERSION").to_string(),
534        }
535    }
536
537    /// Returns a reference to the underlying state store.
538    pub fn state_store(&self) -> &StateStore {
539        &self.store
540    }
541
542    /// Spawns a new thread with the given initial history and persists it.
543    pub fn spawn_thread_with_history(
544        &mut self,
545        model_provider: String,
546        cwd: PathBuf,
547        initial_history: InitialHistory,
548        persist_extended_history: bool,
549    ) -> Result<NewThread> {
550        let id = format!("thread-{}", Uuid::new_v4());
551        let now = chrono::Utc::now().timestamp();
552        let preview = preview_from_initial_history(&initial_history);
553        let source = match initial_history {
554            InitialHistory::New => SessionSource::Interactive,
555            InitialHistory::Forked(_) => SessionSource::Fork,
556            InitialHistory::Resumed { .. } => SessionSource::Resume,
557        };
558        let thread = Thread {
559            id: id.clone(),
560            preview,
561            ephemeral: !persist_extended_history,
562            model_provider: model_provider.clone(),
563            created_at: now,
564            updated_at: now,
565            status: ThreadStatus::Running,
566            path: None,
567            cwd: cwd.clone(),
568            cli_version: self.cli_version.clone(),
569            source: match source {
570                SessionSource::Interactive => codewhale_protocol::SessionSource::Interactive,
571                SessionSource::Resume => codewhale_protocol::SessionSource::Resume,
572                SessionSource::Fork => codewhale_protocol::SessionSource::Fork,
573                SessionSource::Api => codewhale_protocol::SessionSource::Api,
574                SessionSource::Unknown => codewhale_protocol::SessionSource::Unknown,
575            },
576            name: None,
577        };
578        self.persist_thread(&thread, None)?;
579        match &initial_history {
580            InitialHistory::Forked(items) => {
581                for item in items {
582                    self.store.append_message(
583                        &thread.id,
584                        "history",
585                        &item.to_string(),
586                        Some(item.clone()),
587                    )?;
588                }
589            }
590            InitialHistory::Resumed { history, .. } => {
591                for item in history {
592                    self.store.append_message(
593                        &thread.id,
594                        "history",
595                        &item.to_string(),
596                        Some(item.clone()),
597                    )?;
598                }
599            }
600            InitialHistory::New => {}
601        }
602        self.running_threads
603            .insert(thread.id.clone(), thread.clone());
604        Ok(NewThread {
605            thread,
606            model: "auto".to_string(),
607            model_provider,
608            cwd,
609            approval_policy: None,
610            sandbox: None,
611        })
612    }
613
614    /// Resumes an existing thread, returning `None` if not found.
615    pub fn resume_thread_with_history(
616        &mut self,
617        params: &ThreadResumeParams,
618        fallback_cwd: &Path,
619        model_provider: String,
620    ) -> Result<Option<NewThread>> {
621        if params.history.is_none()
622            && let Some(thread) = self.running_threads.get(&params.thread_id).cloned()
623        {
624            return Ok(Some(NewThread {
625                model: params.model.clone().unwrap_or_else(|| "auto".to_string()),
626                model_provider: params.model_provider.clone().unwrap_or(model_provider),
627                cwd: params.cwd.clone().unwrap_or_else(|| thread.cwd.clone()),
628                approval_policy: params.approval_policy.clone(),
629                sandbox: params.sandbox.clone(),
630                thread,
631            }));
632        }
633
634        let persisted = self.store.get_thread(&params.thread_id)?;
635        let Some(metadata) = persisted else {
636            return Ok(None);
637        };
638        let mut thread = to_protocol_thread(metadata);
639        thread.status = ThreadStatus::Running;
640        thread.updated_at = chrono::Utc::now().timestamp();
641        thread.cwd = params
642            .cwd
643            .clone()
644            .unwrap_or_else(|| fallback_cwd.to_path_buf());
645        self.persist_thread(&thread, None)?;
646        self.running_threads
647            .insert(thread.id.clone(), thread.clone());
648        if let Some(history) = params.history.as_ref() {
649            // A read→resume flow hands back items that are already on the
650            // persisted chain; appending them again would double the
651            // conversation on every resume, compounding. Dedup by content
652            // fingerprint (the item's JSON, matching what append_message
653            // stores as content) against the persisted chain and against
654            // items already appended in this loop.
655            let mut seen: HashSet<String> = self
656                .store
657                .list_messages(&thread.id, None)?
658                .into_iter()
659                .map(|message| {
660                    message
661                        .item
662                        .as_ref()
663                        .map_or(message.content.clone(), |item| item.to_string())
664                })
665                .collect();
666            for item in history {
667                let fingerprint = item.to_string();
668                if !seen.insert(fingerprint.clone()) {
669                    continue;
670                }
671                self.store.append_message(
672                    &thread.id,
673                    "history",
674                    &fingerprint,
675                    Some(item.clone()),
676                )?;
677            }
678        }
679
680        Ok(Some(NewThread {
681            model: params.model.clone().unwrap_or_else(|| "auto".to_string()),
682            model_provider: params.model_provider.clone().unwrap_or(model_provider),
683            cwd: thread.cwd.clone(),
684            approval_policy: params.approval_policy.clone(),
685            sandbox: params.sandbox.clone(),
686            thread,
687        }))
688    }
689
690    /// Forks an existing thread into a new one, inheriting the parent's provider.
691    pub fn fork_thread(
692        &mut self,
693        params: &ThreadForkParams,
694        fallback_cwd: &Path,
695    ) -> Result<Option<NewThread>> {
696        let parent = self.store.get_thread(&params.thread_id)?;
697        let Some(parent) = parent else {
698            return Ok(None);
699        };
700        let parent_thread = to_protocol_thread(parent);
701        let new = self.spawn_thread_with_history(
702            params
703                .model_provider
704                .clone()
705                .unwrap_or_else(|| parent_thread.model_provider.clone()),
706            params
707                .cwd
708                .clone()
709                .unwrap_or_else(|| fallback_cwd.to_path_buf()),
710            InitialHistory::Forked(vec![json!({
711                "type": "fork",
712                "from_thread_id": parent_thread.id
713            })]),
714            params.persist_extended_history,
715        )?;
716        Ok(Some(new))
717    }
718
719    /// Lists threads matching the given filter parameters.
720    pub fn list_threads(&self, params: &ThreadListParams) -> Result<Vec<Thread>> {
721        let list = self.store.list_threads(ThreadListFilters {
722            include_archived: params.include_archived,
723            limit: params.limit,
724        })?;
725        Ok(list.into_iter().map(to_protocol_thread).collect())
726    }
727
728    /// Reads a single thread by id, or `None` if not found.
729    pub fn read_thread(&self, params: &ThreadReadParams) -> Result<Option<Thread>> {
730        Ok(self
731            .store
732            .get_thread(&params.thread_id)?
733            .map(to_protocol_thread))
734    }
735
736    /// Sets the display name for a thread, returning the updated thread or `None`.
737    pub fn set_thread_name(&mut self, params: &ThreadSetNameParams) -> Result<Option<Thread>> {
738        let Some(mut metadata) = self.store.get_thread(&params.thread_id)? else {
739            return Ok(None);
740        };
741        metadata.name = Some(params.name.clone());
742        metadata.updated_at = chrono::Utc::now().timestamp();
743        self.store.upsert_thread(&metadata)?;
744        let updated = to_protocol_thread(metadata);
745        self.running_threads
746            .insert(updated.id.clone(), updated.clone());
747        Ok(Some(updated))
748    }
749
750    /// Sets or replaces the persisted goal for a thread.
751    pub fn set_thread_goal(&mut self, params: &ThreadGoalSetParams) -> Result<Option<ThreadGoal>> {
752        if self.store.get_thread(&params.thread_id)?.is_none() {
753            return Ok(None);
754        }
755        let now = chrono::Utc::now().timestamp();
756        let goal = ThreadGoalRecord {
757            thread_id: params.thread_id.clone(),
758            goal_id: format!("goal-{}", Uuid::new_v4()),
759            objective: params.objective.clone(),
760            status: PersistedThreadGoalStatus::Active,
761            token_budget: params.token_budget,
762            tokens_used: 0,
763            time_used_seconds: 0,
764            continuation_count: 0,
765            created_at: now,
766            updated_at: now,
767        };
768        self.store.upsert_thread_goal(&goal)?;
769        Ok(Some(to_protocol_goal(goal)))
770    }
771
772    /// Reads the persisted goal for a thread.
773    pub fn get_thread_goal(&self, params: &ThreadGoalGetParams) -> Result<Option<ThreadGoal>> {
774        Ok(self
775            .store
776            .get_thread_goal(&params.thread_id)?
777            .map(to_protocol_goal))
778    }
779
780    /// Accrues durable per-goal usage and/or a continuation pass for a thread.
781    pub fn record_thread_goal_progress(
782        &mut self,
783        params: &ThreadGoalProgressParams,
784    ) -> Result<Option<ThreadGoal>> {
785        if self.store.get_thread(&params.thread_id)?.is_none() {
786            return Ok(None);
787        }
788
789        let now = chrono::Utc::now().timestamp();
790        let mut goal = if params.token_delta != 0 || params.time_delta_seconds != 0 {
791            self.store.record_thread_goal_usage(
792                &params.thread_id,
793                params.token_delta,
794                params.time_delta_seconds,
795                now,
796            )?
797        } else {
798            self.store.get_thread_goal(&params.thread_id)?
799        };
800
801        if params.record_continuation {
802            goal = self
803                .store
804                .record_thread_goal_continuation(&params.thread_id, now)?;
805        }
806
807        Ok(goal.map(to_protocol_goal))
808    }
809
810    /// Clears the persisted goal for a thread, returning whether one existed.
811    pub fn clear_thread_goal(&mut self, params: &ThreadGoalClearParams) -> Result<bool> {
812        self.store.delete_thread_goal(&params.thread_id)
813    }
814
815    /// Archives a thread so it no longer appears in default listings.
816    pub fn archive_thread(&mut self, thread_id: &str) -> Result<()> {
817        self.store.mark_archived(thread_id)?;
818        if let Some(thread) = self.running_threads.get_mut(thread_id) {
819            thread.status = ThreadStatus::Archived;
820        }
821        Ok(())
822    }
823
824    /// Restores an archived thread to active status.
825    pub fn unarchive_thread(&mut self, thread_id: &str) -> Result<()> {
826        self.store.mark_unarchived(thread_id)?;
827        if let Some(metadata) = self.store.get_thread(thread_id)? {
828            let thread = to_protocol_thread(metadata);
829            if let Some(cached) = self.running_threads.get_mut(thread_id) {
830                *cached = thread;
831            }
832        }
833        Ok(())
834    }
835
836    /// Records a user message in a thread and updates its preview and timestamp.
837    pub fn touch_message(&mut self, thread_id: &str, input: &str) -> Result<()> {
838        let Some(mut metadata) = self.store.get_thread(thread_id)? else {
839            return Ok(());
840        };
841        metadata.updated_at = chrono::Utc::now().timestamp();
842        metadata.preview = truncate_preview(input);
843        metadata.status = PersistedThreadStatus::Running;
844        self.store.upsert_thread(&metadata)?;
845        if let Some(thread) = self.running_threads.get_mut(thread_id) {
846            thread.updated_at = metadata.updated_at;
847            thread.preview = metadata.preview;
848            thread.status = ThreadStatus::Running;
849        }
850        let message_id = self.store.append_message(thread_id, "user", input, None)?;
851        self.store.save_checkpoint(
852            thread_id,
853            "latest",
854            &json!({
855                "reason": "thread_message",
856                "message_id": message_id,
857                "role": "user",
858                "preview": truncate_preview(input),
859                "updated_at": metadata.updated_at
860            }),
861        )?;
862        Ok(())
863    }
864
865    fn persist_thread(&self, thread: &Thread, rollout_path: Option<PathBuf>) -> Result<()> {
866        // This update payload carries no per-thread policy, so preserve any
867        // policy already stored for the thread rather than erasing it with
868        // NULLs on every persist/resume.
869        let existing = self.store.get_thread(&thread.id)?;
870        self.store.upsert_thread(&ThreadMetadata {
871            id: thread.id.clone(),
872            rollout_path,
873            preview: thread.preview.clone(),
874            ephemeral: thread.ephemeral,
875            model_provider: thread.model_provider.clone(),
876            created_at: thread.created_at,
877            updated_at: thread.updated_at,
878            status: to_persisted_status(&thread.status),
879            path: thread.path.clone(),
880            cwd: thread.cwd.clone(),
881            cli_version: thread.cli_version.clone(),
882            source: to_persisted_source(&thread.source),
883            name: thread.name.clone(),
884            sandbox_policy: existing
885                .as_ref()
886                .and_then(|metadata| metadata.sandbox_policy.clone()),
887            approval_mode: existing
888                .as_ref()
889                .and_then(|metadata| metadata.approval_mode.clone()),
890            archived: matches!(thread.status, ThreadStatus::Archived),
891            archived_at: None,
892            git_sha: None,
893            git_branch: None,
894            git_origin_url: None,
895            memory_mode: None,
896            current_leaf_id: None,
897        })
898    }
899}
900
901/// Top-level runtime combining config, model registry, threads, tools, MCP, and hooks.
902pub struct Runtime {
903    /// Resolved application configuration.
904    pub config: ConfigToml,
905    /// Registry of available model providers.
906    pub model_registry: ModelRegistry,
907    /// Manages conversation thread lifecycle.
908    pub thread_manager: ThreadManager,
909    /// Registry of callable tools.
910    pub tool_registry: Arc<ToolRegistry>,
911    /// Manager for MCP server connections.
912    pub mcp_manager: Arc<McpManager>,
913    /// Engine for evaluating execution policy decisions.
914    pub exec_policy: ExecPolicyEngine,
915    /// Dispatcher for lifecycle hooks.
916    pub hooks: HookDispatcher,
917    /// Manager for background job lifecycle.
918    pub jobs: JobManager,
919}
920
921impl Runtime {
922    /// Constructs a new `Runtime`, loading existing jobs from the state store.
923    pub fn new(
924        config: ConfigToml,
925        model_registry: ModelRegistry,
926        state: StateStore,
927        tool_registry: Arc<ToolRegistry>,
928        mcp_manager: Arc<McpManager>,
929        exec_policy: ExecPolicyEngine,
930        hooks: HookDispatcher,
931    ) -> Self {
932        let mut jobs = JobManager::default();
933        if let Err(e) = jobs.load_from_store(&state) {
934            tracing::warn!("Failed to load job store, starting with empty job list: {e}");
935        }
936        Self {
937            config,
938            model_registry,
939            thread_manager: ThreadManager::new(state),
940            tool_registry,
941            mcp_manager,
942            exec_policy,
943            hooks,
944            jobs,
945        }
946    }
947
948    /// Update the live configuration in-place so the next turn picks up
949    /// changes without a restart.  Called by the app-server after
950    /// `ConfigSet` or `ConfigUnset`.
951    ///
952    /// Only `config.toml` is touched by those operations, so the sibling
953    /// `permissions.toml` (and therefore `exec_policy`) is left unchanged.
954    ///
955    /// Fields that the TUI caches on its `App` struct (`api_provider`,
956    /// `reasoning_effort`, `mcp_config_path`, `skills_dir`, …) are read
957    /// live from `self.config` here via `resolve_runtime_options`, so they
958    /// take effect on the next prompt turn without any extra plumbing.
959    pub fn update_config(&mut self, config: ConfigToml) {
960        self.config = config;
961    }
962
963    /// Reload the live configuration **and** the exec policy from a
964    /// freshly-loaded `ConfigStore`.  Used by the app-server's
965    /// `ConfigReload` request, which re-reads both `config.toml` and the
966    /// sibling `permissions.toml` from disk.
967    ///
968    /// Unlike `update_config`, this also refreshes `self.exec_policy` so
969    /// externally edited permission rules take effect without a restart.
970    ///
971    /// Mirrors the TUI `reload_runtime_config` codepath for everything
972    /// that is reachable from the headless `Runtime`. The TUI-only caches
973    /// (`last_effective_reasoning_effort`, `model_compaction_budget`,
974    /// `ui_locale`, …) do not exist on `Runtime` and need no work here.
975    ///
976    /// **Not** refreshed by this call:
977    /// * `mcp_manager` — MCP server connections are loaded once at
978    ///   startup from `mcp_config_path`. Changing `mcp_config_path` or the
979    ///   referenced `mcp.json` still requires a headless-runtime restart;
980    ///   the TUI owns a separate explicit `/mcp reload` operation.
981    /// * `tool_registry` — built once at startup.
982    /// * `model_registry` — static catalog.
983    pub fn reload_config_and_policy(&mut self, config: ConfigToml, exec_policy: ExecPolicyEngine) {
984        self.config = config;
985        self.exec_policy = exec_policy;
986    }
987
988    fn persisted_thread_data(&self, thread_id: &str) -> Result<Value> {
989        let history = self
990            .thread_manager
991            .state_store()
992            .list_messages(thread_id, Some(500))?
993            .into_iter()
994            .map(|message| {
995                json!({
996                    "id": message.id,
997                    "role": message.role,
998                    "content": message.content,
999                    "item": message.item,
1000                    "created_at": message.created_at
1001                })
1002            })
1003            .collect::<Vec<_>>();
1004
1005        let checkpoint = self
1006            .thread_manager
1007            .state_store()
1008            .load_checkpoint(thread_id, None)?
1009            .map(|record| {
1010                json!({
1011                    "checkpoint_id": record.checkpoint_id,
1012                    "state": record.state,
1013                    "created_at": record.created_at
1014                })
1015            });
1016
1017        let goal = self
1018            .thread_manager
1019            .state_store()
1020            .get_thread_goal(thread_id)?
1021            .map(to_protocol_goal);
1022
1023        Ok(json!({
1024            "history": history,
1025            "checkpoint": checkpoint,
1026            "goal": goal
1027        }))
1028    }
1029
1030    /// Dispatches a thread request (create, start, resume, fork, list, read, etc.).
1031    pub async fn handle_thread(&mut self, req: ThreadRequest) -> Result<ThreadResponse> {
1032        match req {
1033            ThreadRequest::Create { .. } => {
1034                let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1035                let new = self.thread_manager.spawn_thread_with_history(
1036                    "deepseek".to_string(),
1037                    cwd,
1038                    InitialHistory::New,
1039                    false,
1040                )?;
1041                let mut response = thread_response_from_new("created", new);
1042                response.data = self.persisted_thread_data(&response.thread_id)?;
1043                Ok(response)
1044            }
1045            ThreadRequest::Start(params) => {
1046                let cwd = params.cwd.clone().unwrap_or_else(|| {
1047                    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
1048                });
1049                let new = self.thread_manager.spawn_thread_with_history(
1050                    params
1051                        .model_provider
1052                        .clone()
1053                        .unwrap_or_else(|| "deepseek".to_string()),
1054                    cwd,
1055                    InitialHistory::New,
1056                    params.persist_extended_history,
1057                )?;
1058                let mut response = thread_response_from_new("started", new);
1059                response.data = self.persisted_thread_data(&response.thread_id)?;
1060                Ok(response)
1061            }
1062            ThreadRequest::Resume(params) => {
1063                let fallback_cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1064                if let Some(new) = self.thread_manager.resume_thread_with_history(
1065                    &params,
1066                    &fallback_cwd,
1067                    "deepseek".to_string(),
1068                )? {
1069                    let mut response = thread_response_from_new("resumed", new);
1070                    response.data = self.persisted_thread_data(&response.thread_id)?;
1071                    Ok(response)
1072                } else {
1073                    Ok(ThreadResponse {
1074                        thread_id: params.thread_id,
1075                        status: "missing".to_string(),
1076                        thread: None,
1077                        threads: Vec::new(),
1078                        goal: None,
1079                        model: None,
1080                        model_provider: None,
1081                        cwd: None,
1082                        approval_policy: params.approval_policy,
1083                        sandbox: params.sandbox,
1084                        events: Vec::new(),
1085                        data: json!({"error":"thread not found"}),
1086                    })
1087                }
1088            }
1089            ThreadRequest::Fork(params) => {
1090                let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
1091                if let Some(new) = self.thread_manager.fork_thread(&params, &cwd)? {
1092                    let mut response = thread_response_from_new("forked", new);
1093                    response.data = self.persisted_thread_data(&response.thread_id)?;
1094                    Ok(response)
1095                } else {
1096                    Ok(ThreadResponse {
1097                        thread_id: params.thread_id,
1098                        status: "missing".to_string(),
1099                        thread: None,
1100                        threads: Vec::new(),
1101                        goal: None,
1102                        model: None,
1103                        model_provider: None,
1104                        cwd: None,
1105                        approval_policy: params.approval_policy,
1106                        sandbox: params.sandbox,
1107                        events: Vec::new(),
1108                        data: json!({"error":"thread not found"}),
1109                    })
1110                }
1111            }
1112            ThreadRequest::List(params) => Ok(ThreadResponse {
1113                thread_id: "list".to_string(),
1114                status: "ok".to_string(),
1115                thread: None,
1116                threads: self.thread_manager.list_threads(&params)?,
1117                goal: None,
1118                model: None,
1119                model_provider: None,
1120                cwd: None,
1121                approval_policy: None,
1122                sandbox: None,
1123                events: Vec::new(),
1124                data: json!({}),
1125            }),
1126            ThreadRequest::Read(params) => {
1127                let id = params.thread_id.clone();
1128                let data = self.persisted_thread_data(&id)?;
1129                Ok(ThreadResponse {
1130                    thread_id: id,
1131                    status: "ok".to_string(),
1132                    thread: self.thread_manager.read_thread(&params)?,
1133                    threads: Vec::new(),
1134                    goal: self.thread_manager.get_thread_goal(&ThreadGoalGetParams {
1135                        thread_id: params.thread_id,
1136                    })?,
1137                    model: None,
1138                    model_provider: None,
1139                    cwd: None,
1140                    approval_policy: None,
1141                    sandbox: None,
1142                    events: Vec::new(),
1143                    data,
1144                })
1145            }
1146            ThreadRequest::SetName(params) => Ok(ThreadResponse {
1147                thread_id: params.thread_id.clone(),
1148                status: "ok".to_string(),
1149                thread: self.thread_manager.set_thread_name(&params)?,
1150                threads: Vec::new(),
1151                goal: None,
1152                model: None,
1153                model_provider: None,
1154                cwd: None,
1155                approval_policy: None,
1156                sandbox: None,
1157                events: Vec::new(),
1158                data: json!({}),
1159            }),
1160            ThreadRequest::GoalSet(params) => {
1161                let thread_id = params.thread_id.clone();
1162                if let Some(goal) = self.thread_manager.set_thread_goal(&params)? {
1163                    Ok(ThreadResponse {
1164                        thread_id,
1165                        status: "ok".to_string(),
1166                        thread: None,
1167                        threads: Vec::new(),
1168                        goal: Some(goal.clone()),
1169                        model: None,
1170                        model_provider: None,
1171                        cwd: None,
1172                        approval_policy: None,
1173                        sandbox: None,
1174                        events: vec![EventFrame::ThreadGoalUpdated { goal: goal.clone() }],
1175                        data: json!({ "goal": goal }),
1176                    })
1177                } else {
1178                    Ok(ThreadResponse {
1179                        thread_id,
1180                        status: "missing".to_string(),
1181                        thread: None,
1182                        threads: Vec::new(),
1183                        goal: None,
1184                        model: None,
1185                        model_provider: None,
1186                        cwd: None,
1187                        approval_policy: None,
1188                        sandbox: None,
1189                        events: Vec::new(),
1190                        data: json!({"error":"thread not found"}),
1191                    })
1192                }
1193            }
1194            ThreadRequest::GoalGet(params) => {
1195                let goal = self.thread_manager.get_thread_goal(&params)?;
1196                Ok(ThreadResponse {
1197                    thread_id: params.thread_id,
1198                    status: "ok".to_string(),
1199                    thread: None,
1200                    threads: Vec::new(),
1201                    goal: goal.clone(),
1202                    model: None,
1203                    model_provider: None,
1204                    cwd: None,
1205                    approval_policy: None,
1206                    sandbox: None,
1207                    events: Vec::new(),
1208                    data: json!({ "goal": goal }),
1209                })
1210            }
1211            ThreadRequest::GoalClear(params) => {
1212                let thread_id = params.thread_id.clone();
1213                let cleared = self.thread_manager.clear_thread_goal(&params)?;
1214                Ok(ThreadResponse {
1215                    thread_id: thread_id.clone(),
1216                    status: if cleared { "cleared" } else { "empty" }.to_string(),
1217                    thread: None,
1218                    threads: Vec::new(),
1219                    goal: None,
1220                    model: None,
1221                    model_provider: None,
1222                    cwd: None,
1223                    approval_policy: None,
1224                    sandbox: None,
1225                    events: if cleared {
1226                        vec![EventFrame::ThreadGoalCleared { thread_id }]
1227                    } else {
1228                        Vec::new()
1229                    },
1230                    data: json!({ "cleared": cleared }),
1231                })
1232            }
1233            ThreadRequest::GoalRecordProgress(params) => {
1234                let thread_id = params.thread_id.clone();
1235                if let Some(goal) = self.thread_manager.record_thread_goal_progress(&params)? {
1236                    Ok(ThreadResponse {
1237                        thread_id,
1238                        status: "ok".to_string(),
1239                        thread: None,
1240                        threads: Vec::new(),
1241                        goal: Some(goal.clone()),
1242                        model: None,
1243                        model_provider: None,
1244                        cwd: None,
1245                        approval_policy: None,
1246                        sandbox: None,
1247                        events: vec![EventFrame::ThreadGoalUpdated { goal: goal.clone() }],
1248                        data: json!({ "goal": goal }),
1249                    })
1250                } else {
1251                    Ok(ThreadResponse {
1252                        thread_id,
1253                        status: "missing".to_string(),
1254                        thread: None,
1255                        threads: Vec::new(),
1256                        goal: None,
1257                        model: None,
1258                        model_provider: None,
1259                        cwd: None,
1260                        approval_policy: None,
1261                        sandbox: None,
1262                        events: Vec::new(),
1263                        data: json!({"error":"thread or goal not found"}),
1264                    })
1265                }
1266            }
1267            ThreadRequest::Archive { thread_id } => {
1268                self.thread_manager.archive_thread(&thread_id)?;
1269                Ok(ThreadResponse {
1270                    thread_id,
1271                    status: "archived".to_string(),
1272                    thread: None,
1273                    threads: Vec::new(),
1274                    goal: None,
1275                    model: None,
1276                    model_provider: None,
1277                    cwd: None,
1278                    approval_policy: None,
1279                    sandbox: None,
1280                    events: Vec::new(),
1281                    data: json!({}),
1282                })
1283            }
1284            ThreadRequest::Unarchive { thread_id } => {
1285                self.thread_manager.unarchive_thread(&thread_id)?;
1286                Ok(ThreadResponse {
1287                    thread_id,
1288                    status: "unarchived".to_string(),
1289                    thread: None,
1290                    threads: Vec::new(),
1291                    goal: None,
1292                    model: None,
1293                    model_provider: None,
1294                    cwd: None,
1295                    approval_policy: None,
1296                    sandbox: None,
1297                    events: Vec::new(),
1298                    data: json!({}),
1299                })
1300            }
1301            // A thread message is a *turn*, and this type is not the turn
1302            // engine — it owns thread bookkeeping and persistence only. The
1303            // app-server routes messages through its runtime bridge
1304            // (`POST /v1/threads/{id}/turns` on the runtime API) and never
1305            // reaches this arm. Returning an error rather than a canned
1306            // "accepted" keeps any other caller from mistaking bookkeeping
1307            // for execution.
1308            ThreadRequest::Message { thread_id, .. } => Err(anyhow!(
1309                "thread message for {thread_id} cannot be executed here: \
1310                 Runtime::handle_thread does not run turns. Send it through the \
1311                 app-server runtime bridge (POST /v1/threads/{{id}}/turns)."
1312            )),
1313        }
1314    }
1315
1316    /// Evaluates execution policy and dispatches a tool call.
1317    pub async fn invoke_tool(
1318        &self,
1319        call: ToolCall,
1320        approval_mode: AskForApproval,
1321        cwd: &Path,
1322    ) -> Result<Value> {
1323        let fallback_cwd = cwd.display().to_string();
1324        let (command, policy_cwd, execution_kind) = call.execution_subject(&fallback_cwd);
1325        let policy_tool = match &call.payload {
1326            ToolPayload::LocalShell { .. } => "exec_shell",
1327            _ => call.name.as_str(),
1328        };
1329        let policy_path = permission_path_for_call(&call);
1330        let decision = self.exec_policy.check(ExecPolicyContext {
1331            command: &command,
1332            cwd: &policy_cwd,
1333            tool: Some(policy_tool),
1334            path: policy_path.as_deref(),
1335            ask_for_approval: approval_mode,
1336            sandbox_mode: None,
1337        })?;
1338        let precheck = policy_precheck_payload(&decision, &command, &policy_cwd, execution_kind);
1339        let response_id = format!("tool-{}", Uuid::new_v4());
1340        let call_id = call
1341            .raw_tool_call_id
1342            .clone()
1343            .unwrap_or_else(|| format!("tool-call-{}", Uuid::new_v4()));
1344        self.hooks
1345            .emit(HookEvent::ToolLifecycle {
1346                response_id: response_id.clone(),
1347                tool_name: call.name.clone(),
1348                phase: "precheck".to_string(),
1349                payload: precheck.clone(),
1350            })
1351            .await;
1352
1353        if !decision.allow {
1354            let reason = decision.reason().to_string();
1355            let approval_id = format!("approval-{}", Uuid::new_v4());
1356            let error_frame = EventFrame::Error {
1357                response_id: response_id.clone(),
1358                message: reason.clone(),
1359            };
1360            self.hooks
1361                .emit(HookEvent::ApprovalLifecycle {
1362                    approval_id,
1363                    phase: "denied".to_string(),
1364                    reason: Some(reason.clone()),
1365                })
1366                .await;
1367            self.hooks
1368                .emit(HookEvent::GenericEventFrame {
1369                    frame: Box::new(error_frame.clone()),
1370                })
1371                .await;
1372            return Ok(json!({
1373                "ok": false,
1374                "status": "denied",
1375                "execution_kind": execution_kind,
1376                "response_id": response_id,
1377                "precheck": precheck,
1378                "error": reason,
1379                "events": [event_frame_payload(&error_frame)],
1380            }));
1381        }
1382
1383        if decision.requires_approval {
1384            let approval_id = format!("approval-{}", Uuid::new_v4());
1385            let reason = decision.reason().to_string();
1386            let maybe_approval_frame = approval_request_frame(
1387                &decision.requirement,
1388                decision.matched_rule.as_deref(),
1389                call_id,
1390                approval_id.clone(),
1391                response_id.clone(),
1392                command.clone(),
1393                policy_cwd.clone(),
1394            );
1395            self.hooks
1396                .emit(HookEvent::ApprovalLifecycle {
1397                    approval_id: approval_id.clone(),
1398                    phase: "requested".to_string(),
1399                    reason: Some(reason.clone()),
1400                })
1401                .await;
1402            let mut events = Vec::new();
1403            if let Some(frame) = maybe_approval_frame {
1404                self.hooks
1405                    .emit(HookEvent::GenericEventFrame {
1406                        frame: Box::new(frame.clone()),
1407                    })
1408                    .await;
1409                events.push(event_frame_payload(&frame));
1410            }
1411            return Ok(json!({
1412                "ok": false,
1413                "status": "approval_required",
1414                "execution_kind": execution_kind,
1415                "response_id": response_id,
1416                "approval_id": approval_id,
1417                "precheck": precheck,
1418                "error": reason,
1419                "events": events,
1420            }));
1421        }
1422
1423        // Headless `request_user_input`: mirror the approval fire-and-return
1424        // branch (issue #3102). The TUI intercepts this tool by name before
1425        // dispatch and blocks on a reply channel; the headless runtime instead
1426        // emits a typed `UserInputRequest` frame and returns a
1427        // `user_input_required` status so the client can render the question.
1428        // It does NOT block — consistent with the headless approval model,
1429        // which has no resume channel either.
1430        //
1431        // The reply goes to the runtime API
1432        // (`POST /v1/user-input/{thread_id}/{request_id}`), which owns the
1433        // pending request and can resume the turn. The app-server control
1434        // transport cannot: it executes only `thread/interrupt` mid-turn, so
1435        // an answer sent over it would queue behind the very turn that is
1436        // waiting for it. `AppRequest::SubmitUserInput` therefore refuses
1437        // explicitly instead of pretending to have delivered the answer.
1438        if call.name == REQUEST_USER_INPUT_TOOL_NAME {
1439            let request_id = format!("user-input-{}", Uuid::new_v4());
1440            let arguments = match &call.payload {
1441                ToolPayload::Function { arguments } => arguments.as_str(),
1442                // Custom/Mcp/LocalShell can't carry a user_input payload; fall
1443                // through to the generic dispatch error below.
1444                _ => "",
1445            };
1446            let maybe_frame = user_input_request_frame(
1447                call_id.clone(),
1448                response_id.clone(),
1449                request_id.clone(),
1450                arguments,
1451            );
1452            let mut events = Vec::new();
1453            if let Some(frame) = maybe_frame {
1454                self.hooks
1455                    .emit(HookEvent::GenericEventFrame {
1456                        frame: Box::new(frame.clone()),
1457                    })
1458                    .await;
1459                events.push(event_frame_payload(&frame));
1460            }
1461            return Ok(json!({
1462                "ok": false,
1463                "status": "user_input_required",
1464                "execution_kind": execution_kind,
1465                "response_id": response_id,
1466                "request_id": request_id,
1467                "precheck": precheck,
1468                "events": events,
1469            }));
1470        }
1471
1472        let start_frame = EventFrame::ToolCallStart {
1473            response_id: response_id.clone(),
1474            tool_name: call.name.clone(),
1475            arguments: tool_payload_value(&call.payload),
1476        };
1477        self.hooks
1478            .emit(HookEvent::GenericEventFrame {
1479                frame: Box::new(start_frame.clone()),
1480            })
1481            .await;
1482        self.hooks
1483            .emit(HookEvent::ToolLifecycle {
1484                response_id: response_id.clone(),
1485                tool_name: call.name.clone(),
1486                phase: "dispatching".to_string(),
1487                payload: json!({
1488                    "call_id": call_id,
1489                    "execution_kind": execution_kind
1490                }),
1491            })
1492            .await;
1493
1494        match time::timeout(
1495            tool_dispatch_timeout(),
1496            self.tool_registry.dispatch(call.clone(), true),
1497        )
1498        .await
1499        {
1500            Ok(Ok(tool_output)) => {
1501                let success = tool_output.success();
1502                let status = if success { "completed" } else { "failed" };
1503                let result_frame = EventFrame::ToolCallResult {
1504                    response_id: response_id.clone(),
1505                    tool_name: call.name.clone(),
1506                    output: tool_output_value(&tool_output),
1507                };
1508                self.hooks
1509                    .emit(HookEvent::GenericEventFrame {
1510                        frame: Box::new(result_frame.clone()),
1511                    })
1512                    .await;
1513                self.hooks
1514                    .emit(HookEvent::ToolLifecycle {
1515                        response_id: response_id.clone(),
1516                        tool_name: call.name,
1517                        phase: status.to_string(),
1518                        payload: json!({ "ok": success }),
1519                    })
1520                    .await;
1521                Ok(json!({
1522                    "ok": success,
1523                    "status": status,
1524                    "execution_kind": execution_kind,
1525                    "response_id": response_id,
1526                    "precheck": precheck,
1527                    "output": tool_output,
1528                    "events": [
1529                        event_frame_payload(&start_frame),
1530                        event_frame_payload(&result_frame)
1531                    ]
1532                }))
1533            }
1534            Ok(Err(err)) => {
1535                let message = format!("{err:?}");
1536                let error_frame = EventFrame::Error {
1537                    response_id: response_id.clone(),
1538                    message: message.clone(),
1539                };
1540                self.hooks
1541                    .emit(HookEvent::GenericEventFrame {
1542                        frame: Box::new(error_frame.clone()),
1543                    })
1544                    .await;
1545                self.hooks
1546                    .emit(HookEvent::ToolLifecycle {
1547                        response_id: response_id.clone(),
1548                        tool_name: call.name,
1549                        phase: "failed".to_string(),
1550                        payload: json!({ "error": message.clone() }),
1551                    })
1552                    .await;
1553                Ok(json!({
1554                    "ok": false,
1555                    "status": "failed",
1556                    "execution_kind": execution_kind,
1557                    "response_id": response_id,
1558                    "precheck": precheck,
1559                    "error": message,
1560                    "events": [
1561                        event_frame_payload(&start_frame),
1562                        event_frame_payload(&error_frame)
1563                    ]
1564                }))
1565            }
1566            Err(_elapsed) => {
1567                let seconds = tool_dispatch_timeout().as_secs().max(1);
1568                let message = format!("Tool '{}' timed out after {seconds}s", call.name);
1569                let error_frame = EventFrame::Error {
1570                    response_id: response_id.clone(),
1571                    message: message.clone(),
1572                };
1573                self.hooks
1574                    .emit(HookEvent::GenericEventFrame {
1575                        frame: Box::new(error_frame.clone()),
1576                    })
1577                    .await;
1578                self.hooks
1579                    .emit(HookEvent::ToolLifecycle {
1580                        response_id: response_id.clone(),
1581                        tool_name: call.name,
1582                        phase: "failed".to_string(),
1583                        payload: json!({ "error": message.clone(), "timeout": true }),
1584                    })
1585                    .await;
1586                Ok(json!({
1587                    "ok": false,
1588                    "status": "timeout",
1589                    "execution_kind": execution_kind,
1590                    "response_id": response_id,
1591                    "precheck": precheck,
1592                    "error": message,
1593                    "events": [
1594                        event_frame_payload(&start_frame),
1595                        event_frame_payload(&error_frame)
1596                    ]
1597                }))
1598            }
1599        }
1600    }
1601
1602    /// Starts all configured MCP servers and emits startup events via hooks.
1603    pub async fn mcp_startup(&self) -> McpStartupCompleteEvent {
1604        let mut updates = Vec::new();
1605        let summary = self.mcp_manager.start_all(|update| {
1606            updates.push(update);
1607        });
1608        for update in updates {
1609            let status = match update.status {
1610                McpManagerStartupStatus::Starting => codewhale_protocol::McpStartupStatus::Starting,
1611                McpManagerStartupStatus::Ready => codewhale_protocol::McpStartupStatus::Ready,
1612                McpManagerStartupStatus::Failed { error } => {
1613                    codewhale_protocol::McpStartupStatus::Failed { error }
1614                }
1615                McpManagerStartupStatus::Cancelled => {
1616                    codewhale_protocol::McpStartupStatus::Cancelled
1617                }
1618            };
1619            self.hooks
1620                .emit(HookEvent::GenericEventFrame {
1621                    frame: Box::new(EventFrame::McpStartupUpdate {
1622                        update: codewhale_protocol::McpStartupUpdateEvent {
1623                            server_name: update.server_name,
1624                            status,
1625                        },
1626                    }),
1627                })
1628                .await;
1629        }
1630        self.hooks
1631            .emit(HookEvent::GenericEventFrame {
1632                frame: Box::new(EventFrame::McpStartupComplete {
1633                    summary: codewhale_protocol::McpStartupCompleteEvent {
1634                        ready: summary.ready.clone(),
1635                        failed: summary
1636                            .failed
1637                            .iter()
1638                            .map(|f| codewhale_protocol::McpStartupFailure {
1639                                server_name: f.server_name.clone(),
1640                                error: f.error.clone(),
1641                            })
1642                            .collect(),
1643                        cancelled: summary.cancelled.clone(),
1644                    },
1645                }),
1646            })
1647            .await;
1648        summary
1649    }
1650
1651    /// Returns the current application status including all jobs and their history.
1652    pub fn app_status(&self) -> AppResponse {
1653        let jobs = self.jobs.list();
1654        let events = jobs
1655            .iter()
1656            .flat_map(|job| {
1657                job.history.iter().map(|entry| EventFrame::ResponseDelta {
1658                    response_id: job.id.clone(),
1659                    delta: json!({
1660                        "kind": "job_transition",
1661                        "job_id": job.id.clone(),
1662                        "phase": entry.phase.clone(),
1663                        "status": job_status_to_str(entry.status),
1664                        "progress": entry.progress,
1665                        "detail": entry.detail.clone(),
1666                        "retry": job_retry_to_value(&entry.retry),
1667                        "at": entry.at
1668                    })
1669                    .to_string(),
1670                    channel: ResponseChannel::Text,
1671                })
1672            })
1673            .collect::<Vec<_>>();
1674        AppResponse {
1675            ok: true,
1676            data: json!({
1677                "jobs": jobs.into_iter().map(|job| {
1678                    json!({
1679                        "id": job.id,
1680                        "name": job.name,
1681                        "status": job_status_to_str(job.status),
1682                        "progress": job.progress,
1683                        "detail": job.detail,
1684                        "retry": job_retry_to_value(&job.retry),
1685                        "history": job.history.iter().map(job_history_to_value).collect::<Vec<_>>()
1686                    })
1687                }).collect::<Vec<_>>()
1688            }),
1689            events,
1690        }
1691    }
1692
1693    /// Returns the default model provider from the resolved configuration.
1694    pub fn provider_default(&self) -> ProviderKind {
1695        self.config.provider
1696    }
1697
1698    /// Saves a named checkpoint for a thread.
1699    pub fn save_thread_checkpoint(
1700        &self,
1701        thread_id: &str,
1702        checkpoint_id: &str,
1703        state: &Value,
1704    ) -> Result<()> {
1705        self.thread_manager
1706            .state_store()
1707            .save_checkpoint(thread_id, checkpoint_id, state)
1708    }
1709
1710    /// Loads a checkpoint for a thread. Pass `None` for the latest.
1711    pub fn load_thread_checkpoint(
1712        &self,
1713        thread_id: &str,
1714        checkpoint_id: Option<&str>,
1715    ) -> Result<Option<Value>> {
1716        Ok(self
1717            .thread_manager
1718            .state_store()
1719            .load_checkpoint(thread_id, checkpoint_id)?
1720            .map(|checkpoint| checkpoint.state))
1721    }
1722
1723    /// Enqueues a new background job and persists it immediately.
1724    pub fn enqueue_job(&mut self, name: impl Into<String>) -> Result<JobRecord> {
1725        let job = self.jobs.enqueue(name);
1726        self.jobs
1727            .persist_job(self.thread_manager.state_store(), &job.id)?;
1728        Ok(job)
1729    }
1730
1731    /// Transitions a job to running and persists the change.
1732    pub fn set_job_running(&mut self, job_id: &str) -> Result<()> {
1733        self.jobs.set_running(job_id);
1734        self.jobs
1735            .persist_job(self.thread_manager.state_store(), job_id)
1736    }
1737
1738    /// Updates a job's progress and persists the change.
1739    pub fn update_job_progress(
1740        &mut self,
1741        job_id: &str,
1742        progress: u8,
1743        detail: Option<String>,
1744    ) -> Result<()> {
1745        self.jobs.update_progress(job_id, progress, detail);
1746        self.jobs
1747            .persist_job(self.thread_manager.state_store(), job_id)
1748    }
1749
1750    /// Marks a job as completed and persists the change.
1751    pub fn complete_job(&mut self, job_id: &str) -> Result<()> {
1752        self.jobs.complete(job_id);
1753        self.jobs
1754            .persist_job(self.thread_manager.state_store(), job_id)
1755    }
1756
1757    /// Marks a job as failed and persists the change.
1758    pub fn fail_job(&mut self, job_id: &str, detail: impl Into<String>) -> Result<()> {
1759        self.jobs.fail(job_id, detail);
1760        self.jobs
1761            .persist_job(self.thread_manager.state_store(), job_id)
1762    }
1763
1764    /// Cancels a job and persists the change.
1765    pub fn cancel_job(&mut self, job_id: &str) -> Result<()> {
1766        self.jobs.cancel(job_id);
1767        self.jobs
1768            .persist_job(self.thread_manager.state_store(), job_id)
1769    }
1770
1771    /// Pauses a job and persists the change.
1772    pub fn pause_job(&mut self, job_id: &str, detail: Option<String>) -> Result<()> {
1773        self.jobs.pause(job_id, detail);
1774        self.jobs
1775            .persist_job(self.thread_manager.state_store(), job_id)
1776    }
1777
1778    /// Resumes a paused job and persists the change.
1779    pub fn resume_job(&mut self, job_id: &str, detail: Option<String>) -> Result<()> {
1780        self.jobs.resume(job_id, detail);
1781        self.jobs
1782            .persist_job(self.thread_manager.state_store(), job_id)
1783    }
1784
1785    /// Returns the state-transition history for a job.
1786    pub fn job_history(&self, job_id: &str) -> Vec<JobHistoryEntry> {
1787        self.jobs.history(job_id)
1788    }
1789}
1790
1791fn thread_response_from_new(status: &str, new: NewThread) -> ThreadResponse {
1792    ThreadResponse {
1793        thread_id: new.thread.id.clone(),
1794        status: status.to_string(),
1795        thread: Some(new.thread),
1796        threads: Vec::new(),
1797        goal: None,
1798        model: Some(new.model),
1799        model_provider: Some(new.model_provider),
1800        cwd: Some(new.cwd),
1801        approval_policy: new.approval_policy,
1802        sandbox: new.sandbox,
1803        events: Vec::new(),
1804        data: json!({}),
1805    }
1806}
1807
1808fn preview_from_initial_history(initial_history: &InitialHistory) -> String {
1809    match initial_history {
1810        InitialHistory::New => "New conversation".to_string(),
1811        InitialHistory::Forked(items) => truncate_preview(
1812            &items
1813                .first()
1814                .map(Value::to_string)
1815                .unwrap_or_else(|| "Forked conversation".to_string()),
1816        ),
1817        InitialHistory::Resumed { history, .. } => truncate_preview(
1818            &history
1819                .first()
1820                .map(Value::to_string)
1821                .unwrap_or_else(|| "Resumed conversation".to_string()),
1822        ),
1823    }
1824}
1825
1826fn permission_path_for_call(call: &ToolCall) -> Option<String> {
1827    match &call.payload {
1828        ToolPayload::Function { arguments } => serde_json::from_str::<Value>(arguments)
1829            .ok()
1830            .and_then(|value| {
1831                value
1832                    .get("path")
1833                    .and_then(Value::as_str)
1834                    .map(str::to_string)
1835            }),
1836        ToolPayload::Mcp { raw_arguments, .. } => raw_arguments
1837            .get("path")
1838            .and_then(Value::as_str)
1839            .map(str::to_string),
1840        ToolPayload::Custom { .. } | ToolPayload::LocalShell { .. } => None,
1841    }
1842}
1843
1844fn truncate_preview(value: &str) -> String {
1845    value.chars().take(120).collect()
1846}
1847
1848fn to_protocol_thread(thread: ThreadMetadata) -> Thread {
1849    Thread {
1850        id: thread.id,
1851        preview: thread.preview,
1852        ephemeral: thread.ephemeral,
1853        model_provider: thread.model_provider,
1854        created_at: thread.created_at,
1855        updated_at: thread.updated_at,
1856        status: match thread.status {
1857            PersistedThreadStatus::Running => ThreadStatus::Running,
1858            PersistedThreadStatus::Idle => ThreadStatus::Idle,
1859            PersistedThreadStatus::Completed => ThreadStatus::Completed,
1860            PersistedThreadStatus::Failed => ThreadStatus::Failed,
1861            PersistedThreadStatus::Paused => ThreadStatus::Paused,
1862            PersistedThreadStatus::Archived => ThreadStatus::Archived,
1863        },
1864        path: thread.path,
1865        cwd: thread.cwd,
1866        cli_version: thread.cli_version,
1867        source: match thread.source {
1868            SessionSource::Interactive => codewhale_protocol::SessionSource::Interactive,
1869            SessionSource::Resume => codewhale_protocol::SessionSource::Resume,
1870            SessionSource::Fork => codewhale_protocol::SessionSource::Fork,
1871            SessionSource::Api => codewhale_protocol::SessionSource::Api,
1872            SessionSource::Unknown => codewhale_protocol::SessionSource::Unknown,
1873        },
1874        name: thread.name,
1875    }
1876}
1877
1878fn to_protocol_goal(goal: ThreadGoalRecord) -> ThreadGoal {
1879    ThreadGoal {
1880        thread_id: goal.thread_id,
1881        goal_id: goal.goal_id,
1882        objective: goal.objective,
1883        status: to_protocol_goal_status(goal.status),
1884        token_budget: goal.token_budget,
1885        tokens_used: goal.tokens_used,
1886        time_used_seconds: goal.time_used_seconds,
1887        continuation_count: goal.continuation_count,
1888        created_at: goal.created_at,
1889        updated_at: goal.updated_at,
1890    }
1891}
1892
1893fn to_protocol_goal_status(status: PersistedThreadGoalStatus) -> ThreadGoalStatus {
1894    match status {
1895        PersistedThreadGoalStatus::Active => ThreadGoalStatus::Active,
1896        PersistedThreadGoalStatus::Paused => ThreadGoalStatus::Paused,
1897        PersistedThreadGoalStatus::Blocked => ThreadGoalStatus::Blocked,
1898        PersistedThreadGoalStatus::UsageLimited => ThreadGoalStatus::UsageLimited,
1899        PersistedThreadGoalStatus::BudgetLimited => ThreadGoalStatus::BudgetLimited,
1900        PersistedThreadGoalStatus::Complete => ThreadGoalStatus::Complete,
1901    }
1902}
1903
1904fn to_persisted_status(status: &ThreadStatus) -> PersistedThreadStatus {
1905    match status {
1906        ThreadStatus::Running => PersistedThreadStatus::Running,
1907        ThreadStatus::Idle => PersistedThreadStatus::Idle,
1908        ThreadStatus::Completed => PersistedThreadStatus::Completed,
1909        ThreadStatus::Failed => PersistedThreadStatus::Failed,
1910        ThreadStatus::Paused => PersistedThreadStatus::Paused,
1911        ThreadStatus::Archived => PersistedThreadStatus::Archived,
1912    }
1913}
1914
1915fn to_persisted_source(source: &codewhale_protocol::SessionSource) -> SessionSource {
1916    match source {
1917        codewhale_protocol::SessionSource::Interactive => SessionSource::Interactive,
1918        codewhale_protocol::SessionSource::Resume => SessionSource::Resume,
1919        codewhale_protocol::SessionSource::Fork => SessionSource::Fork,
1920        codewhale_protocol::SessionSource::Api => SessionSource::Api,
1921        codewhale_protocol::SessionSource::Unknown => SessionSource::Unknown,
1922    }
1923}
1924
1925fn approval_request_frame(
1926    requirement: &ExecApprovalRequirement,
1927    matched_rule: Option<&str>,
1928    call_id: String,
1929    approval_id: String,
1930    turn_id: String,
1931    command: String,
1932    cwd: String,
1933) -> Option<EventFrame> {
1934    let ExecApprovalRequirement::NeedsApproval {
1935        reason,
1936        proposed_execpolicy_amendment,
1937        proposed_network_policy_amendments,
1938    } = requirement
1939    else {
1940        return None;
1941    };
1942
1943    let mut available_decisions = vec![
1944        ReviewDecision::Approved,
1945        ReviewDecision::ApprovedForSession,
1946        ReviewDecision::Denied,
1947        ReviewDecision::Abort,
1948    ];
1949    if proposed_execpolicy_amendment
1950        .as_ref()
1951        .is_some_and(|amendment| !amendment.prefixes.is_empty())
1952    {
1953        available_decisions.push(ReviewDecision::ApprovedExecpolicyAmendment);
1954    }
1955    available_decisions.extend(proposed_network_policy_amendments.iter().cloned().map(
1956        |amendment| ReviewDecision::NetworkPolicyAmendment {
1957            host: amendment.host,
1958            action: amendment.action,
1959        },
1960    ));
1961
1962    Some(EventFrame::ExecApprovalRequest {
1963        request: ExecApprovalRequestEvent {
1964            call_id,
1965            approval_id,
1966            turn_id,
1967            command,
1968            cwd,
1969            reason: reason.clone(),
1970            matched_rule: matched_rule.map(|rule| rule.to_string().into_boxed_str()),
1971            network_approval_context: None,
1972            proposed_execpolicy_amendment: proposed_execpolicy_amendment
1973                .as_ref()
1974                .map(|amendment| amendment.prefixes.clone())
1975                .unwrap_or_default(),
1976            proposed_network_policy_amendments: proposed_network_policy_amendments.clone(),
1977            additional_permissions: Vec::new(),
1978            available_decisions,
1979        },
1980    })
1981}
1982
1983/// Build an [`EventFrame::UserInputRequest`] for a headless
1984/// `request_user_input` tool call, mirroring [`approval_request_frame`].
1985///
1986/// `arguments` is the raw JSON arguments string the model supplied to the
1987/// `request_user_input` tool (a `ToolPayload::Function` body). On parse
1988/// failure we return `None` so the caller falls through to the generic tool
1989/// error path rather than silently dropping the request.
1990fn user_input_request_frame(
1991    call_id: String,
1992    turn_id: String,
1993    request_id: String,
1994    arguments: &str,
1995) -> Option<EventFrame> {
1996    let parsed: Value = serde_json::from_str(arguments).ok()?;
1997    // Extract the `questions` array and lift it into the headless event
1998    // shape. We tolerate missing `allow_free_text`/`multi_select` (default
1999    // false) and extra fields, matching the lenient TUI `from_value` path.
2000    let questions = parsed.get("questions").cloned().filter(Value::is_array)?;
2001    let request = UserInputRequestEvent {
2002        call_id,
2003        turn_id,
2004        request_id,
2005        questions: serde_json::from_value(questions).ok()?,
2006    };
2007    Some(EventFrame::UserInputRequest { request })
2008}
2009
2010fn approval_requirement_payload(requirement: &ExecApprovalRequirement) -> Value {
2011    match requirement {
2012        ExecApprovalRequirement::Skip {
2013            bypass_sandbox,
2014            proposed_execpolicy_amendment,
2015        } => json!({
2016            "type": "skip",
2017            "bypass_sandbox": bypass_sandbox,
2018            "reason": requirement.reason(),
2019            "proposed_execpolicy_amendment": proposed_execpolicy_amendment
2020                .as_ref()
2021                .map(|amendment| amendment.prefixes.clone())
2022                .unwrap_or_default()
2023        }),
2024        ExecApprovalRequirement::NeedsApproval {
2025            reason,
2026            proposed_execpolicy_amendment,
2027            proposed_network_policy_amendments,
2028        } => json!({
2029            "type": "needs_approval",
2030            "reason": reason,
2031            "proposed_execpolicy_amendment": proposed_execpolicy_amendment
2032                .as_ref()
2033                .map(|amendment| amendment.prefixes.clone())
2034                .unwrap_or_default(),
2035            "proposed_network_policy_amendments": proposed_network_policy_amendments
2036        }),
2037        ExecApprovalRequirement::Forbidden { reason } => json!({
2038            "type": "forbidden",
2039            "reason": reason
2040        }),
2041    }
2042}
2043
2044fn policy_precheck_payload(
2045    decision: &ExecPolicyDecision,
2046    command: &str,
2047    cwd: &str,
2048    execution_kind: &str,
2049) -> Value {
2050    json!({
2051        "execution_kind": execution_kind,
2052        "command": command,
2053        "cwd": cwd,
2054        "allow": decision.allow,
2055        "requires_approval": decision.requires_approval,
2056        "matched_rule": decision.matched_rule.clone(),
2057        "phase": decision.requirement.phase(),
2058        "reason": decision.reason(),
2059        "requirement": approval_requirement_payload(&decision.requirement)
2060    })
2061}
2062
2063fn tool_payload_value(payload: &ToolPayload) -> Value {
2064    serde_json::to_value(payload).unwrap_or_else(
2065        |_| json!({"type":"serialization_error","message":"tool payload unavailable"}),
2066    )
2067}
2068
2069fn tool_output_value(output: &codewhale_protocol::ToolOutput) -> Value {
2070    serde_json::to_value(output).unwrap_or_else(
2071        |_| json!({"type":"serialization_error","message":"tool output unavailable"}),
2072    )
2073}
2074
2075fn event_frame_payload(frame: &EventFrame) -> Value {
2076    serde_json::to_value(frame)
2077        .unwrap_or_else(|_| json!({"event":"error","message":"failed to encode event frame"}))
2078}
2079
2080/// Tool name that triggers the headless clarification-question flow.
2081///
2082/// Mirrors the TUI's `REQUEST_USER_INPUT_NAME`
2083/// (`crates/tui/src/core/engine/tool_catalog.rs`); duplicated here rather than
2084/// depended on across crates so `core` stays free of `tui` imports.
2085const REQUEST_USER_INPUT_TOOL_NAME: &str = "request_user_input";
2086
2087fn json_optional_string(value: &Value) -> Option<String> {
2088    if value.is_null() {
2089        None
2090    } else {
2091        value.as_str().map(ToString::to_string)
2092    }
2093}
2094
2095fn parse_retry_metadata(value: Option<&Value>) -> JobRetryMetadata {
2096    let Some(value) = value else {
2097        return JobRetryMetadata::default();
2098    };
2099    JobRetryMetadata {
2100        attempt: value
2101            .get("attempt")
2102            .and_then(Value::as_u64)
2103            .unwrap_or(0)
2104            .min(u32::MAX as u64) as u32,
2105        max_attempts: value
2106            .get("max_attempts")
2107            .and_then(Value::as_u64)
2108            .unwrap_or(DEFAULT_JOB_MAX_ATTEMPTS as u64)
2109            .min(u32::MAX as u64) as u32,
2110        backoff_base_ms: value
2111            .get("backoff_base_ms")
2112            .and_then(Value::as_u64)
2113            .unwrap_or(DEFAULT_JOB_BACKOFF_BASE_MS),
2114        next_backoff_ms: value
2115            .get("next_backoff_ms")
2116            .and_then(Value::as_u64)
2117            .unwrap_or(0),
2118        next_retry_at: value.get("next_retry_at").and_then(Value::as_i64),
2119    }
2120}
2121
2122fn parse_history_entry(value: &Value) -> Option<JobHistoryEntry> {
2123    let status = value
2124        .get("status")
2125        .and_then(Value::as_str)
2126        .and_then(job_status_from_str)?;
2127    Some(JobHistoryEntry {
2128        at: value.get("at").and_then(Value::as_i64).unwrap_or(0),
2129        phase: value
2130            .get("phase")
2131            .and_then(Value::as_str)
2132            .unwrap_or("unknown")
2133            .to_string(),
2134        status,
2135        progress: value
2136            .get("progress")
2137            .and_then(Value::as_u64)
2138            .map(|v| v.min(u8::MAX as u64) as u8),
2139        detail: value.get("detail").and_then(json_optional_string),
2140        retry: parse_retry_metadata(value.get("retry")),
2141    })
2142}
2143
2144fn job_status_to_str(status: JobStatus) -> &'static str {
2145    match status {
2146        JobStatus::Queued => "queued",
2147        JobStatus::Running => "running",
2148        JobStatus::Paused => "paused",
2149        JobStatus::Completed => "completed",
2150        JobStatus::Failed => "failed",
2151        JobStatus::Cancelled => "cancelled",
2152    }
2153}
2154
2155fn job_status_from_str(value: &str) -> Option<JobStatus> {
2156    match value {
2157        "queued" => Some(JobStatus::Queued),
2158        "running" => Some(JobStatus::Running),
2159        "paused" => Some(JobStatus::Paused),
2160        "completed" => Some(JobStatus::Completed),
2161        "failed" => Some(JobStatus::Failed),
2162        "cancelled" => Some(JobStatus::Cancelled),
2163        _ => None,
2164    }
2165}
2166
2167fn job_retry_to_value(retry: &JobRetryMetadata) -> Value {
2168    json!({
2169        "attempt": retry.attempt,
2170        "max_attempts": retry.max_attempts,
2171        "backoff_base_ms": retry.backoff_base_ms,
2172        "next_backoff_ms": retry.next_backoff_ms,
2173        "next_retry_at": retry.next_retry_at
2174    })
2175}
2176
2177fn job_history_to_value(entry: &JobHistoryEntry) -> Value {
2178    json!({
2179        "at": entry.at,
2180        "phase": entry.phase.clone(),
2181        "status": job_status_to_str(entry.status),
2182        "progress": entry.progress,
2183        "detail": entry.detail.clone(),
2184        "retry": job_retry_to_value(&entry.retry)
2185    })
2186}
2187
2188fn runtime_status_to_job_state(status: JobStatus) -> JobStateStatus {
2189    match status {
2190        JobStatus::Queued => JobStateStatus::Queued,
2191        JobStatus::Running => JobStateStatus::Running,
2192        JobStatus::Paused => JobStateStatus::Paused,
2193        JobStatus::Completed => JobStateStatus::Completed,
2194        JobStatus::Failed => JobStateStatus::Failed,
2195        JobStatus::Cancelled => JobStateStatus::Cancelled,
2196    }
2197}
2198
2199fn job_state_status_to_runtime(status: JobStateStatus) -> JobStatus {
2200    match status {
2201        JobStateStatus::Queued => JobStatus::Queued,
2202        JobStateStatus::Running => JobStatus::Running,
2203        JobStateStatus::Paused => JobStatus::Paused,
2204        JobStateStatus::Completed => JobStatus::Completed,
2205        JobStateStatus::Failed => JobStatus::Failed,
2206        JobStateStatus::Cancelled => JobStatus::Cancelled,
2207    }
2208}
2209
2210#[cfg(test)]
2211mod tests {
2212    use super::*;
2213    use codewhale_protocol::ThreadResumeParams;
2214    use codewhale_tools::ToolCallSource;
2215
2216    fn temp_core_state(name: &str) -> StateStore {
2217        let dir =
2218            std::env::temp_dir().join(format!("codewhale-core-{name}-{}", Uuid::new_v4().simple()));
2219        std::fs::create_dir_all(&dir).expect("create temp state dir");
2220        StateStore::open(Some(dir.join("state.db"))).expect("open state store")
2221    }
2222
2223    fn test_thread_metadata(id: &str) -> ThreadMetadata {
2224        ThreadMetadata {
2225            id: id.to_string(),
2226            rollout_path: None,
2227            preview: "test thread".to_string(),
2228            ephemeral: false,
2229            model_provider: "deepseek".to_string(),
2230            created_at: 10,
2231            updated_at: 10,
2232            status: PersistedThreadStatus::Running,
2233            path: None,
2234            cwd: PathBuf::from("/tmp/codewhale"),
2235            cli_version: "0.0.0-test".to_string(),
2236            source: SessionSource::Interactive,
2237            name: None,
2238            sandbox_policy: None,
2239            approval_mode: None,
2240            archived: false,
2241            archived_at: None,
2242            git_sha: None,
2243            git_branch: None,
2244            git_origin_url: None,
2245            memory_mode: None,
2246            current_leaf_id: None,
2247        }
2248    }
2249
2250    // ── JobManager: lifecycle ──────────────────────────────────────────
2251
2252    #[test]
2253    fn permission_path_for_call_extracts_function_path_argument() {
2254        let call = ToolCall {
2255            name: "read_file".to_string(),
2256            payload: ToolPayload::Function {
2257                arguments: json!({ "path": "README.md" }).to_string(),
2258            },
2259            source: ToolCallSource::Direct,
2260            raw_tool_call_id: None,
2261        };
2262
2263        assert_eq!(
2264            permission_path_for_call(&call).as_deref(),
2265            Some("README.md")
2266        );
2267    }
2268
2269    #[test]
2270    fn permission_path_for_call_extracts_mcp_path_argument() {
2271        let call = ToolCall {
2272            name: "mcp_fs_read".to_string(),
2273            payload: ToolPayload::Mcp {
2274                server: "fs".to_string(),
2275                tool: "read".to_string(),
2276                raw_arguments: json!({ "path": "secrets/token.txt" }),
2277                raw_tool_call_id: None,
2278            },
2279            source: ToolCallSource::Direct,
2280            raw_tool_call_id: None,
2281        };
2282
2283        assert_eq!(
2284            permission_path_for_call(&call).as_deref(),
2285            Some("secrets/token.txt")
2286        );
2287    }
2288
2289    #[test]
2290    fn permission_path_for_call_ignores_shell_payload() {
2291        let call = ToolCall {
2292            name: "exec_shell".to_string(),
2293            payload: ToolPayload::LocalShell {
2294                params: codewhale_protocol::LocalShellParams {
2295                    command: "cargo test".to_string(),
2296                    cwd: None,
2297                    timeout_ms: None,
2298                },
2299            },
2300            source: ToolCallSource::Direct,
2301            raw_tool_call_id: None,
2302        };
2303
2304        assert_eq!(permission_path_for_call(&call), None);
2305    }
2306
2307    #[test]
2308    fn thread_goal_progress_accumulates_durable_accounting() {
2309        let store = temp_core_state("thread-goal-progress");
2310        store
2311            .upsert_thread(&test_thread_metadata("thread-1"))
2312            .expect("upsert thread");
2313        let mut manager = ThreadManager::new(store);
2314        manager
2315            .set_thread_goal(&ThreadGoalSetParams {
2316                thread_id: "thread-1".to_string(),
2317                objective: "Carry the goal across turns".to_string(),
2318                token_budget: Some(2_000),
2319            })
2320            .expect("set goal")
2321            .expect("goal exists");
2322
2323        let updated = manager
2324            .record_thread_goal_progress(&ThreadGoalProgressParams {
2325                thread_id: "thread-1".to_string(),
2326                token_delta: 750,
2327                time_delta_seconds: 12,
2328                record_continuation: true,
2329            })
2330            .expect("record progress")
2331            .expect("goal exists");
2332
2333        assert_eq!(updated.tokens_used, 750);
2334        assert_eq!(updated.time_used_seconds, 12);
2335        assert_eq!(updated.continuation_count, 1);
2336
2337        let persisted = manager
2338            .get_thread_goal(&ThreadGoalGetParams {
2339                thread_id: "thread-1".to_string(),
2340            })
2341            .expect("read goal")
2342            .expect("goal exists");
2343        assert_eq!(persisted.tokens_used, 750);
2344        assert_eq!(persisted.time_used_seconds, 12);
2345        assert_eq!(persisted.continuation_count, 1);
2346    }
2347
2348    #[test]
2349    fn approval_request_frame_includes_matched_rule() {
2350        let requirement = ExecApprovalRequirement::NeedsApproval {
2351            reason: "Typed ask rule 'tool=exec_shell command=cargo test' requires approval."
2352                .to_string(),
2353            proposed_execpolicy_amendment: None,
2354            proposed_network_policy_amendments: Vec::new(),
2355        };
2356
2357        let frame = approval_request_frame(
2358            &requirement,
2359            Some("tool=exec_shell command=cargo test"),
2360            "call-1".to_string(),
2361            "approval-1".to_string(),
2362            "turn-1".to_string(),
2363            "cargo test --workspace".to_string(),
2364            "/repo".to_string(),
2365        )
2366        .expect("approval frame");
2367
2368        let EventFrame::ExecApprovalRequest { request } = frame else {
2369            panic!("expected exec approval request frame");
2370        };
2371        assert_eq!(
2372            request.matched_rule.as_deref(),
2373            Some("tool=exec_shell command=cargo test")
2374        );
2375        assert_eq!(request.reason, requirement.reason());
2376    }
2377
2378    #[test]
2379    fn user_input_request_frame_lifts_questions_from_arguments() {
2380        // issue #3102: the headless frame constructor must parse the model's
2381        // `request_user_input` arguments and lift the questions into the
2382        // UserInputRequestEvent, defaulting the boolean flags when omitted.
2383        let arguments = r#"{"questions":[{"header":"Scope","id":"scope","question":"Which?","options":[{"label":"A","description":"a"},{"label":"B","description":"b"}],"allow_free_text":true}]}"#;
2384        let frame = user_input_request_frame(
2385            "call-1".to_string(),
2386            "turn-1".to_string(),
2387            "ui-1".to_string(),
2388            arguments,
2389        )
2390        .expect("user input frame");
2391
2392        let EventFrame::UserInputRequest { request } = frame else {
2393            panic!("expected user_input_request frame");
2394        };
2395        assert_eq!(request.call_id, "call-1");
2396        assert_eq!(request.turn_id, "turn-1");
2397        assert_eq!(request.request_id, "ui-1");
2398        assert_eq!(request.questions.len(), 1);
2399        assert_eq!(request.questions[0].id, "scope");
2400        assert!(request.questions[0].allow_free_text);
2401        // multi_select omitted in the payload → defaults to false.
2402        assert!(!request.questions[0].multi_select);
2403        assert_eq!(request.questions[0].options.len(), 2);
2404    }
2405
2406    #[test]
2407    fn user_input_request_frame_returns_none_on_invalid_arguments() {
2408        // On parse failure the constructor returns None so invoke_tool falls
2409        // through to the generic tool error path instead of silently dropping.
2410        let frame = user_input_request_frame(
2411            "call-1".to_string(),
2412            "turn-1".to_string(),
2413            "ui-1".to_string(),
2414            "not json",
2415        );
2416        assert!(frame.is_none());
2417
2418        // Valid JSON but missing the questions array is also rejected.
2419        let frame = user_input_request_frame(
2420            "call-1".to_string(),
2421            "turn-1".to_string(),
2422            "ui-1".to_string(),
2423            r#"{"foo":"bar"}"#,
2424        );
2425        assert!(frame.is_none());
2426    }
2427
2428    #[test]
2429    fn enqueue_creates_queued_job_with_zero_progress() {
2430        let mut jm = JobManager::default();
2431        let job = jm.enqueue("build");
2432        assert_eq!(job.name, "build");
2433        assert_eq!(job.status, JobStatus::Queued);
2434        assert_eq!(job.progress, Some(0));
2435        assert!(job.detail.is_none());
2436        assert_eq!(job.history.len(), 1);
2437        assert_eq!(job.history[0].phase, "created");
2438    }
2439
2440    #[test]
2441    fn set_running_transitions_from_queued() {
2442        let mut jm = JobManager::default();
2443        let job = jm.enqueue("deploy");
2444        let id = job.id.clone();
2445        jm.set_running(&id);
2446        let jobs = jm.list();
2447        let updated = jobs.iter().find(|j| j.id == id).unwrap();
2448        assert_eq!(updated.status, JobStatus::Running);
2449        assert_eq!(updated.history.last().unwrap().phase, "running");
2450    }
2451
2452    #[test]
2453    fn update_progress_clamps_to_100() {
2454        let mut jm = JobManager::default();
2455        let job = jm.enqueue("task");
2456        let id = job.id.clone();
2457        jm.update_progress(&id, 150, Some("over".to_string()));
2458        let jobs = jm.list();
2459        let updated = jobs.iter().find(|j| j.id == id).unwrap();
2460        assert_eq!(updated.progress, Some(100));
2461    }
2462
2463    #[test]
2464    fn complete_sets_progress_to_100() {
2465        let mut jm = JobManager::default();
2466        let job = jm.enqueue("task");
2467        let id = job.id.clone();
2468        jm.set_running(&id);
2469        jm.complete(&id);
2470        let jobs = jm.list();
2471        let updated = jobs.iter().find(|j| j.id == id).unwrap();
2472        assert_eq!(updated.status, JobStatus::Completed);
2473        assert_eq!(updated.progress, Some(100));
2474    }
2475
2476    #[test]
2477    fn fail_increments_attempt_and_sets_backoff() {
2478        let mut jm = JobManager::default();
2479        let job = jm.enqueue("fragile");
2480        let id = job.id.clone();
2481        jm.set_running(&id);
2482        jm.fail(&id, "crashed");
2483        let jobs = jm.list();
2484        let updated = jobs.iter().find(|j| j.id == id).unwrap();
2485        assert_eq!(updated.status, JobStatus::Failed);
2486        assert_eq!(updated.retry.attempt, 1);
2487        assert!(updated.retry.next_backoff_ms > 0);
2488        assert!(updated.retry.next_retry_at.is_some());
2489        assert_eq!(updated.detail.as_deref(), Some("crashed"));
2490    }
2491
2492    #[test]
2493    fn fail_clears_retry_after_max_attempts() {
2494        let mut jm = JobManager::default();
2495        let job = jm.enqueue("fragile");
2496        let id = job.id.clone();
2497        for _ in 0..=DEFAULT_JOB_MAX_ATTEMPTS {
2498            jm.set_running(&id);
2499            jm.fail(&id, "boom");
2500        }
2501        let jobs = jm.list();
2502        let updated = jobs.iter().find(|j| j.id == id).unwrap();
2503        assert_eq!(updated.retry.attempt, DEFAULT_JOB_MAX_ATTEMPTS);
2504        assert_eq!(updated.retry.next_backoff_ms, 0);
2505        assert!(updated.retry.next_retry_at.is_none());
2506    }
2507
2508    #[test]
2509    fn cancel_sets_status_and_clears_retry() {
2510        let mut jm = JobManager::default();
2511        let job = jm.enqueue("task");
2512        let id = job.id.clone();
2513        jm.cancel(&id);
2514        let jobs = jm.list();
2515        let updated = jobs.iter().find(|j| j.id == id).unwrap();
2516        assert_eq!(updated.status, JobStatus::Cancelled);
2517        assert_eq!(updated.retry.next_backoff_ms, 0);
2518    }
2519
2520    #[test]
2521    fn pause_and_resume_round_trip() {
2522        let mut jm = JobManager::default();
2523        let job = jm.enqueue("task");
2524        let id = job.id.clone();
2525        jm.set_running(&id);
2526        jm.pause(&id, Some("waiting".to_string()));
2527        let jobs = jm.list();
2528        let paused = jobs.iter().find(|j| j.id == id).unwrap();
2529        assert_eq!(paused.status, JobStatus::Paused);
2530        assert_eq!(paused.detail.as_deref(), Some("waiting"));
2531
2532        jm.resume(&id, None);
2533        let jobs = jm.list();
2534        let resumed = jobs.iter().find(|j| j.id == id).unwrap();
2535        assert_eq!(resumed.status, JobStatus::Running);
2536        assert_eq!(resumed.history.last().unwrap().phase, "resumed");
2537    }
2538
2539    #[test]
2540    fn list_returns_jobs_sorted_by_updated_at_desc() {
2541        let mut jm = JobManager::default();
2542        jm.enqueue("first");
2543        jm.enqueue("second");
2544        jm.enqueue("third");
2545        let jobs = jm.list();
2546        assert_eq!(jobs.len(), 3);
2547        for window in jobs.windows(2) {
2548            assert!(window[0].updated_at >= window[1].updated_at);
2549        }
2550    }
2551
2552    #[test]
2553    fn history_returns_entries_for_existing_job() {
2554        let mut jm = JobManager::default();
2555        let job = jm.enqueue("task");
2556        let id = job.id.clone();
2557        jm.set_running(&id);
2558        jm.complete(&id);
2559        let history = jm.history(&id);
2560        assert_eq!(history.len(), 3); // created, running, completed
2561        assert_eq!(history[0].phase, "created");
2562        assert_eq!(history[1].phase, "running");
2563        assert_eq!(history[2].phase, "completed");
2564    }
2565
2566    #[test]
2567    fn history_returns_empty_for_unknown_job() {
2568        let jm = JobManager::default();
2569        assert!(jm.history("nonexistent").is_empty());
2570    }
2571
2572    #[test]
2573    fn resume_pending_requeues_running_and_queued() {
2574        let mut jm = JobManager::default();
2575        let _j1 = jm.enqueue("queued_task");
2576        let j2 = jm.enqueue("running_task");
2577        let j3 = jm.enqueue("completed_task");
2578        let id2 = j2.id.clone();
2579        let id3 = j3.id.clone();
2580        jm.set_running(&id2);
2581        jm.set_running(&id3);
2582        jm.complete(&id3);
2583
2584        let resumed = jm.resume_pending();
2585        assert_eq!(resumed.len(), 2);
2586        for job in &resumed {
2587            assert_eq!(job.status, JobStatus::Queued);
2588        }
2589    }
2590
2591    // ── JobManager: backoff ────────────────────────────────────────────
2592
2593    #[test]
2594    fn deterministic_backoff_zero_on_first_attempt() {
2595        let retry = JobRetryMetadata {
2596            attempt: 0,
2597            ..Default::default()
2598        };
2599        assert_eq!(JobManager::deterministic_backoff_ms(&retry), 0);
2600    }
2601
2602    #[test]
2603    fn deterministic_backoff_exponential_growth() {
2604        let base = DEFAULT_JOB_BACKOFF_BASE_MS;
2605        for attempt in 1..=5 {
2606            let retry = JobRetryMetadata {
2607                attempt,
2608                backoff_base_ms: base,
2609                ..Default::default()
2610            };
2611            let expected = base * 2u64.pow(attempt.saturating_sub(1).min(20));
2612            assert_eq!(
2613                JobManager::deterministic_backoff_ms(&retry),
2614                expected,
2615                "attempt {attempt}"
2616            );
2617        }
2618    }
2619
2620    #[test]
2621    fn deterministic_backoff_saturates_at_high_exponent() {
2622        let retry = JobRetryMetadata {
2623            attempt: 63,
2624            backoff_base_ms: 1000,
2625            ..Default::default()
2626        };
2627        // Should not panic; result saturates
2628        let _ = JobManager::deterministic_backoff_ms(&retry);
2629    }
2630
2631    // ── JobManager: history truncation ─────────────────────────────────
2632
2633    #[test]
2634    fn push_history_truncates_beyond_max() {
2635        let mut jm = JobManager::default();
2636        let job = jm.enqueue("task");
2637        let id = job.id.clone();
2638        // Generate more history entries than the limit
2639        for i in 0..(MAX_JOB_HISTORY_ENTRIES + 20) {
2640            jm.update_progress(&id, (i % 100) as u8, Some(format!("step {i}")));
2641        }
2642        let history = jm.history(&id);
2643        assert_eq!(history.len(), MAX_JOB_HISTORY_ENTRIES);
2644    }
2645
2646    // ── JobManager: persistence encoding/parsing ───────────────────────
2647
2648    #[test]
2649    fn encode_and_parse_persisted_detail_round_trip() {
2650        let mut jm = JobManager::default();
2651        let job = jm.enqueue("task");
2652        let id = job.id.clone();
2653        jm.set_running(&id);
2654        jm.fail(&id, "oops");
2655        let job = jm.list().into_iter().find(|j| j.id == id).unwrap();
2656
2657        let encoded = JobManager::encode_persisted_detail(&job).unwrap().unwrap();
2658        let parsed = JobManager::parse_persisted_detail(Some(&encoded)).unwrap();
2659
2660        assert_eq!(parsed.status, job.status);
2661        assert_eq!(parsed.detail, job.detail);
2662        assert_eq!(parsed.retry.attempt, job.retry.attempt);
2663        assert_eq!(parsed.history.len(), job.history.len());
2664    }
2665
2666    #[test]
2667    fn parse_persisted_detail_returns_none_for_none_input() {
2668        assert!(JobManager::parse_persisted_detail(None).is_none());
2669    }
2670
2671    #[test]
2672    fn parse_persisted_detail_returns_none_for_invalid_json() {
2673        assert!(JobManager::parse_persisted_detail(Some("not json")).is_none());
2674    }
2675
2676    // ── Helper functions ───────────────────────────────────────────────
2677
2678    #[test]
2679    fn job_status_round_trip_str() {
2680        let statuses = [
2681            JobStatus::Queued,
2682            JobStatus::Running,
2683            JobStatus::Paused,
2684            JobStatus::Completed,
2685            JobStatus::Failed,
2686            JobStatus::Cancelled,
2687        ];
2688        for status in &statuses {
2689            let s = job_status_to_str(*status);
2690            let parsed = job_status_from_str(s);
2691            assert_eq!(parsed, Some(*status), "round-trip failed for {s:?}");
2692        }
2693    }
2694
2695    #[test]
2696    fn job_status_from_str_returns_none_for_unknown() {
2697        assert_eq!(job_status_from_str("unknown"), None);
2698        assert_eq!(job_status_from_str(""), None);
2699    }
2700
2701    #[test]
2702    fn truncate_preview_limits_to_120_chars() {
2703        let long = "a".repeat(200);
2704        let truncated = truncate_preview(&long);
2705        assert_eq!(truncated.len(), 120);
2706    }
2707
2708    #[test]
2709    fn truncate_preview_preserves_short_strings() {
2710        let short = "hello";
2711        assert_eq!(truncate_preview(short), "hello");
2712    }
2713
2714    #[test]
2715    fn runtime_status_to_job_state_maps_correctly() {
2716        assert_eq!(
2717            runtime_status_to_job_state(JobStatus::Queued),
2718            JobStateStatus::Queued
2719        );
2720        assert_eq!(
2721            runtime_status_to_job_state(JobStatus::Running),
2722            JobStateStatus::Running
2723        );
2724        assert_eq!(
2725            runtime_status_to_job_state(JobStatus::Paused),
2726            JobStateStatus::Paused
2727        );
2728        assert_eq!(
2729            runtime_status_to_job_state(JobStatus::Completed),
2730            JobStateStatus::Completed
2731        );
2732        assert_eq!(
2733            runtime_status_to_job_state(JobStatus::Failed),
2734            JobStateStatus::Failed
2735        );
2736        assert_eq!(
2737            runtime_status_to_job_state(JobStatus::Cancelled),
2738            JobStateStatus::Cancelled
2739        );
2740    }
2741
2742    #[test]
2743    fn job_state_status_to_runtime_maps_correctly() {
2744        assert_eq!(
2745            job_state_status_to_runtime(JobStateStatus::Queued),
2746            JobStatus::Queued
2747        );
2748        assert_eq!(
2749            job_state_status_to_runtime(JobStateStatus::Running),
2750            JobStatus::Running
2751        );
2752        assert_eq!(
2753            job_state_status_to_runtime(JobStateStatus::Paused),
2754            JobStatus::Paused
2755        );
2756        assert_eq!(
2757            job_state_status_to_runtime(JobStateStatus::Completed),
2758            JobStatus::Completed
2759        );
2760        assert_eq!(
2761            job_state_status_to_runtime(JobStateStatus::Failed),
2762            JobStatus::Failed
2763        );
2764        assert_eq!(
2765            job_state_status_to_runtime(JobStateStatus::Cancelled),
2766            JobStatus::Cancelled
2767        );
2768    }
2769
2770    #[test]
2771    fn preview_from_initial_history_new() {
2772        let preview = preview_from_initial_history(&InitialHistory::New);
2773        assert_eq!(preview, "New conversation");
2774    }
2775
2776    #[test]
2777    fn preview_from_initial_history_forked() {
2778        let preview = preview_from_initial_history(&InitialHistory::Forked(vec![json!("hello")]));
2779        assert!(preview.contains("hello"));
2780    }
2781
2782    #[test]
2783    fn preview_from_initial_history_resumed() {
2784        let preview = preview_from_initial_history(&InitialHistory::Resumed {
2785            conversation_id: "test".to_string(),
2786            history: vec![json!("world")],
2787            rollout_path: PathBuf::from("/tmp/test"),
2788        });
2789        assert!(preview.contains("world"));
2790    }
2791
2792    #[test]
2793    fn json_optional_string_handles_null() {
2794        assert!(json_optional_string(&Value::Null).is_none());
2795    }
2796
2797    #[test]
2798    fn json_optional_string_handles_string() {
2799        assert_eq!(
2800            json_optional_string(&Value::String("hello".to_string())),
2801            Some("hello".to_string())
2802        );
2803    }
2804
2805    #[test]
2806    fn json_optional_string_handles_non_string() {
2807        assert!(json_optional_string(&json!(42)).is_none());
2808    }
2809
2810    #[test]
2811    fn parse_retry_metadata_returns_default_for_none() {
2812        let retry = parse_retry_metadata(None);
2813        assert_eq!(retry.attempt, 0);
2814        assert_eq!(retry.max_attempts, DEFAULT_JOB_MAX_ATTEMPTS);
2815        assert_eq!(retry.backoff_base_ms, DEFAULT_JOB_BACKOFF_BASE_MS);
2816    }
2817
2818    #[test]
2819    fn parse_retry_metadata_parses_fields() {
2820        let value = json!({
2821            "attempt": 2,
2822            "max_attempts": 5,
2823            "backoff_base_ms": 1000,
2824            "next_backoff_ms": 2000,
2825            "next_retry_at": 1234567890i64
2826        });
2827        let retry = parse_retry_metadata(Some(&value));
2828        assert_eq!(retry.attempt, 2);
2829        assert_eq!(retry.max_attempts, 5);
2830        assert_eq!(retry.backoff_base_ms, 1000);
2831        assert_eq!(retry.next_backoff_ms, 2000);
2832        assert_eq!(retry.next_retry_at, Some(1234567890));
2833    }
2834
2835    #[test]
2836    fn parse_history_entry_returns_none_without_status() {
2837        let value = json!({"at": 1, "phase": "test"});
2838        assert!(parse_history_entry(&value).is_none());
2839    }
2840
2841    #[test]
2842    fn parse_history_entry_parses_valid_entry() {
2843        let value = json!({
2844            "at": 100,
2845            "phase": "running",
2846            "status": "running",
2847            "progress": 50,
2848            "detail": "working",
2849            "retry": {"attempt": 0, "max_attempts": 3, "backoff_base_ms": 500}
2850        });
2851        let entry = parse_history_entry(&value).unwrap();
2852        assert_eq!(entry.at, 100);
2853        assert_eq!(entry.phase, "running");
2854        assert_eq!(entry.status, JobStatus::Running);
2855        assert_eq!(entry.progress, Some(50));
2856        assert_eq!(entry.detail.as_deref(), Some("working"));
2857    }
2858
2859    #[test]
2860    fn paused_job_persists_as_paused_not_running() {
2861        let store = temp_core_state("paused-persist");
2862        let mut jm = JobManager::default();
2863        let job = jm.enqueue("task");
2864        let id = job.id.clone();
2865        jm.set_running(&id);
2866        jm.pause(&id, Some("waiting".to_string()));
2867        jm.persist_job(&store, &id).expect("persist paused job");
2868
2869        let persisted = store.list_jobs(Some(10)).expect("list jobs");
2870        let record = persisted.iter().find(|job| job.id == id).unwrap();
2871        assert_eq!(record.status, JobStateStatus::Paused);
2872
2873        let mut reloaded = JobManager::default();
2874        reloaded.load_from_store(&store).expect("reload jobs");
2875        let jobs = reloaded.list();
2876        let reloaded_job = jobs.iter().find(|job| job.id == id).unwrap();
2877        assert_eq!(reloaded_job.status, JobStatus::Paused);
2878    }
2879
2880    // ── O1: JobRecord → AgentRunSnapshot adapter ────────────────────────
2881
2882    fn sample_job_record(status: JobStatus, detail: Option<&str>) -> JobRecord {
2883        JobRecord {
2884            id: "job-o1-1".to_string(),
2885            name: "sample".to_string(),
2886            status,
2887            progress: None,
2888            detail: detail.map(str::to_string),
2889            retry: JobRetryMetadata {
2890                attempt: 0,
2891                max_attempts: DEFAULT_JOB_MAX_ATTEMPTS,
2892                backoff_base_ms: DEFAULT_JOB_BACKOFF_BASE_MS,
2893                next_backoff_ms: 0,
2894                next_retry_at: None,
2895            },
2896            history: Vec::new(),
2897            created_at: 1_700_000_000,
2898            updated_at: 1_700_000_042,
2899        }
2900    }
2901
2902    #[test]
2903    fn job_record_to_agent_run_maps_non_terminal_states() {
2904        use codewhale_protocol::agent_run::RunState;
2905
2906        for (status, expected) in [
2907            (JobStatus::Queued, RunState::Queued),
2908            (JobStatus::Running, RunState::Running),
2909            (JobStatus::Paused, RunState::Paused),
2910        ] {
2911            let snapshot = job_record_to_agent_run(&sample_job_record(status, None));
2912            assert!(snapshot.is_coherent());
2913            assert_eq!(snapshot.run_id, "job-o1-1");
2914            assert_eq!(snapshot.parent, None);
2915            assert_eq!(
2916                snapshot.source,
2917                codewhale_protocol::agent_run::RunSource::CoreJob
2918            );
2919            assert_eq!(snapshot.state, expected);
2920            assert!(snapshot.terminal.is_none());
2921            assert!(snapshot.refs.is_empty());
2922            assert_eq!(
2923                snapshot.budget,
2924                codewhale_protocol::agent_run::BudgetSummary::default()
2925            );
2926        }
2927    }
2928
2929    #[test]
2930    fn job_record_to_agent_run_maps_terminal_states_without_fabricating_fields() {
2931        use codewhale_protocol::agent_run::{RunState, TerminalOutcome};
2932
2933        let cases = [
2934            (
2935                JobStatus::Completed,
2936                TerminalOutcome::Completed,
2937                Some("done"),
2938            ),
2939            (JobStatus::Failed, TerminalOutcome::Failed, Some("boom")),
2940            (JobStatus::Cancelled, TerminalOutcome::Cancelled, None),
2941        ];
2942
2943        for (status, outcome, detail) in cases {
2944            let snapshot = job_record_to_agent_run(&sample_job_record(status, detail));
2945            assert!(snapshot.is_coherent());
2946            assert_eq!(snapshot.state, RunState::Terminal);
2947            let terminal = snapshot.terminal.expect("terminal summary");
2948            assert_eq!(terminal.outcome, outcome);
2949            assert_eq!(terminal.ended_at_ms, Some(1_700_000_042_000));
2950            assert_eq!(terminal.detail, None);
2951            assert_eq!(
2952                snapshot.budget,
2953                codewhale_protocol::agent_run::BudgetSummary::default()
2954            );
2955            assert!(snapshot.refs.is_empty());
2956            assert_eq!(snapshot.parent, None);
2957        }
2958    }
2959
2960    #[test]
2961    fn job_record_to_agent_run_does_not_export_unclassified_detail() {
2962        let record = sample_job_record(JobStatus::Failed, Some("owner-private diagnostic"));
2963        let snapshot = job_record_to_agent_run(&record);
2964        let terminal = snapshot.terminal.as_ref().expect("terminal summary");
2965        assert_eq!(terminal.detail, None);
2966        let serialized = serde_json::to_string(&snapshot).expect("serialize snapshot");
2967        assert!(!serialized.contains("owner-private diagnostic"));
2968    }
2969
2970    #[test]
2971    fn job_record_to_agent_run_omits_ended_at_on_updated_at_overflow() {
2972        let mut record = sample_job_record(JobStatus::Completed, Some("ok"));
2973        record.updated_at = i64::MAX;
2974        let snapshot = job_record_to_agent_run(&record);
2975        assert!(snapshot.is_coherent());
2976        let terminal = snapshot.terminal.expect("terminal summary");
2977        assert_eq!(terminal.ended_at_ms, None);
2978    }
2979
2980    #[test]
2981    fn unarchive_thread_updates_running_threads_cache() {
2982        let store = temp_core_state("unarchive-cache");
2983        let mut manager = ThreadManager::new(store);
2984        let spawned = manager
2985            .spawn_thread_with_history(
2986                "deepseek".to_string(),
2987                PathBuf::from("/tmp/codewhale"),
2988                InitialHistory::New,
2989                true,
2990            )
2991            .expect("spawn thread");
2992        let thread_id = spawned.thread.id.clone();
2993        let resume_params = ThreadResumeParams {
2994            thread_id: thread_id.clone(),
2995            history: None,
2996            path: None,
2997            model: None,
2998            model_provider: None,
2999            cwd: None,
3000            approval_policy: None,
3001            sandbox: None,
3002            config: None,
3003            base_instructions: None,
3004            developer_instructions: None,
3005            personality: None,
3006            persist_extended_history: false,
3007        };
3008
3009        manager.archive_thread(&thread_id).expect("archive thread");
3010        let archived = manager
3011            .resume_thread_with_history(
3012                &resume_params,
3013                Path::new("/tmp/codewhale"),
3014                "deepseek".to_string(),
3015            )
3016            .expect("resume archived thread")
3017            .expect("thread in cache");
3018        assert_eq!(archived.thread.status, ThreadStatus::Archived);
3019
3020        manager
3021            .unarchive_thread(&thread_id)
3022            .expect("unarchive thread");
3023        let restored = manager
3024            .resume_thread_with_history(
3025                &resume_params,
3026                Path::new("/tmp/codewhale"),
3027                "deepseek".to_string(),
3028            )
3029            .expect("resume unarchived thread")
3030            .expect("thread in cache");
3031        assert_eq!(restored.thread.status, ThreadStatus::Idle);
3032    }
3033
3034    #[test]
3035    fn resume_with_history_does_not_reappend_persisted_messages() {
3036        // A read→resume flow hands the thread's own history back to
3037        // `thread/resume`; appending it verbatim doubled the conversation on
3038        // every resume, compounding.
3039        let store = temp_core_state("resume-history-dedup");
3040        let mut manager = ThreadManager::new(store);
3041        let history = vec![
3042            json!({"type": "user_message", "message": "hello"}),
3043            json!({"type": "assistant_message", "message": "hi there"}),
3044        ];
3045        let spawned = manager
3046            .spawn_thread_with_history(
3047                "deepseek".to_string(),
3048                PathBuf::from("/tmp/codewhale"),
3049                InitialHistory::Forked(history.clone()),
3050                true,
3051            )
3052            .expect("spawn thread");
3053        let thread_id = spawned.thread.id.clone();
3054        let message_count = |manager: &ThreadManager| {
3055            manager
3056                .state_store()
3057                .list_messages(&thread_id, None)
3058                .expect("list messages")
3059                .len()
3060        };
3061        assert_eq!(message_count(&manager), 2);
3062
3063        let resume_params = ThreadResumeParams {
3064            thread_id: thread_id.clone(),
3065            history: Some(history.clone()),
3066            path: None,
3067            model: None,
3068            model_provider: None,
3069            cwd: None,
3070            approval_policy: None,
3071            sandbox: None,
3072            config: None,
3073            base_instructions: None,
3074            developer_instructions: None,
3075            personality: None,
3076            persist_extended_history: false,
3077        };
3078
3079        // Resuming twice with the same history must be idempotent.
3080        for _ in 0..2 {
3081            manager
3082                .resume_thread_with_history(
3083                    &resume_params,
3084                    Path::new("/tmp/codewhale"),
3085                    "deepseek".to_string(),
3086                )
3087                .expect("resume thread")
3088                .expect("thread found");
3089        }
3090        assert_eq!(
3091            message_count(&manager),
3092            2,
3093            "resume re-appended messages already on the persisted chain"
3094        );
3095
3096        // A genuinely new history item is still appended, exactly once.
3097        let mut extended = history.clone();
3098        extended.push(json!({"type": "user_message", "message": "something new"}));
3099        let resume_params = ThreadResumeParams {
3100            history: Some(extended),
3101            ..resume_params
3102        };
3103        manager
3104            .resume_thread_with_history(
3105                &resume_params,
3106                Path::new("/tmp/codewhale"),
3107                "deepseek".to_string(),
3108            )
3109            .expect("resume thread")
3110            .expect("thread found");
3111        assert_eq!(message_count(&manager), 3);
3112    }
3113
3114    #[test]
3115    fn persist_thread_preserves_stored_policy() {
3116        // persist_thread's update payload carries no per-thread policy;
3117        // writing NULLs unconditionally erased any policy stored earlier
3118        // (e.g. on every resume).
3119        let store = temp_core_state("persist-policy");
3120        let mut metadata = test_thread_metadata("thread-policy");
3121        metadata.sandbox_policy = Some("workspace-write".to_string());
3122        metadata.approval_mode = Some("on-request".to_string());
3123        store.upsert_thread(&metadata).expect("seed thread");
3124
3125        // A fresh manager has an empty running-thread cache, so resume goes
3126        // through the persisted path, which calls persist_thread.
3127        let mut manager = ThreadManager::new(store);
3128        let resume_params = ThreadResumeParams {
3129            thread_id: "thread-policy".to_string(),
3130            history: None,
3131            path: None,
3132            model: None,
3133            model_provider: None,
3134            cwd: None,
3135            approval_policy: None,
3136            sandbox: None,
3137            config: None,
3138            base_instructions: None,
3139            developer_instructions: None,
3140            personality: None,
3141            persist_extended_history: false,
3142        };
3143        manager
3144            .resume_thread_with_history(
3145                &resume_params,
3146                Path::new("/tmp/codewhale"),
3147                "deepseek".to_string(),
3148            )
3149            .expect("resume thread")
3150            .expect("thread found");
3151
3152        let persisted = manager
3153            .state_store()
3154            .get_thread("thread-policy")
3155            .expect("read thread")
3156            .expect("thread persisted");
3157        assert_eq!(persisted.sandbox_policy.as_deref(), Some("workspace-write"));
3158        assert_eq!(persisted.approval_mode.as_deref(), Some("on-request"));
3159    }
3160
3161    #[tokio::test]
3162    async fn invoke_tool_returns_timeout_status_for_slow_tools() {
3163        use async_trait::async_trait;
3164        use codewhale_agent::ModelRegistry;
3165        use codewhale_config::ConfigToml;
3166        use codewhale_execpolicy::{AskForApproval, ExecPolicyEngine};
3167        use codewhale_hooks::HookDispatcher;
3168        use codewhale_mcp::McpManager;
3169        use codewhale_protocol::{ToolKind, ToolOutput, ToolPayload};
3170        use codewhale_tools::{FunctionCallError, ToolDescriptor, ToolHandler, ToolInvocation};
3171
3172        struct SlowTool;
3173        #[async_trait]
3174        impl ToolHandler for SlowTool {
3175            fn kind(&self) -> ToolKind {
3176                ToolKind::Function
3177            }
3178
3179            async fn handle(
3180                &self,
3181                _invocation: ToolInvocation,
3182            ) -> std::result::Result<ToolOutput, FunctionCallError> {
3183                time::sleep(Duration::from_millis(200)).await;
3184                Ok(ToolOutput::Function {
3185                    body: Some(json!("late")),
3186                    success: true,
3187                })
3188            }
3189        }
3190
3191        let mut registry = ToolRegistry::default();
3192        registry
3193            .register(
3194                ToolDescriptor {
3195                    name: "slow_tool".to_string(),
3196                    input_schema: json!({"type":"object"}),
3197                    output_schema: json!({"type":"object"}),
3198                    supports_parallel_tool_calls: true,
3199                    timeout_ms: None,
3200                },
3201                Arc::new(SlowTool),
3202            )
3203            .expect("register slow tool");
3204
3205        let runtime = Runtime::new(
3206            ConfigToml::default(),
3207            ModelRegistry::default(),
3208            temp_core_state("invoke-tool-timeout"),
3209            Arc::new(registry),
3210            Arc::new(McpManager::default()),
3211            ExecPolicyEngine::new(vec![], vec![]),
3212            HookDispatcher::default(),
3213        );
3214
3215        let result = runtime
3216            .invoke_tool(
3217                ToolCall {
3218                    name: "slow_tool".to_string(),
3219                    payload: ToolPayload::Function {
3220                        arguments: "{}".to_string(),
3221                    },
3222                    source: ToolCallSource::Direct,
3223                    raw_tool_call_id: None,
3224                },
3225                AskForApproval::Never,
3226                Path::new("/tmp/codewhale"),
3227            )
3228            .await
3229            .expect("invoke tool");
3230
3231        assert_eq!(result["status"], "timeout");
3232        assert_eq!(result["ok"], false);
3233    }
3234
3235    #[tokio::test]
3236    async fn thread_message_is_refused_rather_than_faked() {
3237        // This arm used to record the user message, emit canned
3238        // ResponseStart/ResponseDelta("queued")/ResponseEnd frames and report
3239        // status "accepted" — with no worker, no model, and nothing queued.
3240        // `Runtime` owns thread bookkeeping, not the turn engine, so the only
3241        // honest answer here is a refusal that names where turns actually run.
3242        let mut runtime = Runtime::new(
3243            ConfigToml::default(),
3244            ModelRegistry::default(),
3245            temp_core_state("message-refused"),
3246            Arc::new(ToolRegistry::default()),
3247            Arc::new(McpManager::default()),
3248            ExecPolicyEngine::new(vec![], vec![]),
3249            HookDispatcher::default(),
3250        );
3251        let spawned = runtime
3252            .thread_manager
3253            .spawn_thread_with_history(
3254                "deepseek".to_string(),
3255                PathBuf::from("/tmp/codewhale"),
3256                InitialHistory::New,
3257                true,
3258            )
3259            .expect("spawn thread");
3260        let thread_id = spawned.thread.id.clone();
3261
3262        let err = runtime
3263            .handle_thread(ThreadRequest::Message {
3264                thread_id: thread_id.clone(),
3265                input: "run this".to_string(),
3266            })
3267            .await
3268            .expect_err("handle_thread must not pretend to execute a turn");
3269        assert!(
3270            err.to_string().contains("/v1/threads/{id}/turns"),
3271            "the refusal must name the surface that does run turns: {err}"
3272        );
3273
3274        // Nothing was written to history on the way out.
3275        let history = runtime
3276            .thread_manager
3277            .store
3278            .list_messages(&thread_id, None)
3279            .expect("list messages");
3280        assert!(
3281            history.is_empty(),
3282            "a refused message must leave no history rows: {history:?}"
3283        );
3284    }
3285}