Skip to main content

basis_tasks/
client.rs

1//! `Tasks`: the crate's front door.
2//!
3//! One workspace's durable tasks, over one global [`DataDir`]. `spawn` mints
4//! a task and returns immediately — the mint is a `mkdir` and an atomic
5//! write, nothing durable ever blocks on a model. Everything that *drives* a
6//! task (`ask`, `wait`, `wait_message`) attaches only when no other process
7//! already holds it, and every other verb (`send`, `cancel`, `watch`,
8//! `list`, `terminal`, ...) only ever reads or writes small files under the
9//! attach lock's protection, never taking it. No verb here leaves a resident
10//! process behind (ADR-0019).
11//!
12//! `workspace` matters to exactly two of these: [`spawn`](Tasks::spawn),
13//! which mints under it, and [`list`](Tasks::list), which scans it. Every
14//! other method takes a [`TaskHandle`] that already names its own workspace
15//! key, and resolves purely from that — a host holding a handle can `wait`
16//! or `cancel` it regardless of which workspace `Tasks::open` was given.
17
18use std::{
19    path::{Path, PathBuf},
20    sync::Arc,
21    time::Duration,
22};
23
24use serde_json::Value;
25
26use crate::{
27    Error, Hint,
28    approve::PromptHost,
29    attach,
30    data_dir::{self, DataDir, canonical_workspace},
31    events::EventTail,
32    handle::TaskHandle,
33    inbox,
34    live::{DriveContext, LiveSink},
35    lock, policy,
36    spec::{Continuation, DEFAULT_DEADLINE, RunSpec},
37    state::{self, InboxRecord, RunOptions, TaskMeta, TerminalRecord},
38    stop::Stop,
39    tasks::{self, TaskSummary},
40    watch::EventCursor,
41};
42
43/// The current attach's outcome, or a bounded timeout — see
44/// [`attach::WaitOutcome`], which this re-exports as the return type of
45/// [`Tasks::wait`] and [`Tasks::wait_message`].
46pub use attach::WaitOutcome;
47
48/// What [`Tasks::ask`] enqueued and what came of waiting for it.
49///
50/// `message_id` is the durable correlation handle — the same id [`Tasks::send`]
51/// would have returned for the enqueue alone — carried back so a caller can
52/// retry through [`Tasks::wait_message`] if the wait itself times out, or
53/// report it in an "accepted" record either way.
54#[derive(Debug, Clone, PartialEq)]
55pub struct Reply {
56    pub message_id: String,
57    pub outcome: WaitOutcome,
58}
59
60/// One workspace's durable tasks.
61///
62/// `Clone` because a handful of this type's own `async fn`s need an owned
63/// copy to move onto a blocking thread (see `blocking`, below) — every field
64/// is already cheap to clone (a path, an `Arc`), so this costs nothing a
65/// caller could not already do by hand.
66#[derive(Clone)]
67pub struct Tasks {
68    data: DataDir,
69    workspace: PathBuf,
70    prompt_host: Option<Arc<dyn PromptHost>>,
71    stop: Option<Stop>,
72}
73
74impl Tasks {
75    /// Opens the durable task store: `BASIS_DATA_DIR`, else an absolute
76    /// `XDG_DATA_HOME`, else the platform data home (created private on first
77    /// use). `workspace` is read by [`spawn`](Self::spawn) and
78    /// [`list`](Self::list) only; every handle-scoped method resolves
79    /// straight from the handle, so opening `Tasks` is cheap and does not
80    /// itself touch `workspace` on disk.
81    pub fn open(workspace: impl Into<PathBuf>) -> Result<Self, Error> {
82        let data = DataDir::discover()
83            .map_err(|error| Error::new(format!("open task data directory: {error}")))?;
84        Ok(Self {
85            data,
86            workspace: workspace.into(),
87            prompt_host: None,
88            stop: None,
89        })
90    }
91
92    /// Opens the durable task store at an explicit root, bypassing the
93    /// `BASIS_DATA_DIR`/XDG discovery [`open`](Self::open) performs.
94    ///
95    /// For a host that manages its own data directory location rather than
96    /// the process environment — several `Tasks` in one process, each with
97    /// its own root, for one — and for a test that wants no dependency on
98    /// `std::env` at all.
99    pub fn open_at(
100        data_dir: impl Into<PathBuf>,
101        workspace: impl Into<PathBuf>,
102    ) -> Result<Self, Error> {
103        let data = DataDir::from_path(data_dir.into())
104            .map_err(|error| Error::new(format!("open task data directory: {error}")))?;
105        Ok(Self {
106            data,
107            workspace: workspace.into(),
108            prompt_host: None,
109            stop: None,
110        })
111    }
112
113    /// Supplies how this `Tasks` answers `Approve::Prompt` while it drives a
114    /// task, and whether it can be asked at all — see [`PromptHost`]. Without
115    /// one, `Prompt` refuses the same way an unaskable process always did;
116    /// `basis-cli` is the first caller of this.
117    #[must_use]
118    pub fn with_prompt_host(self, prompt_host: Arc<dyn PromptHost>) -> Self {
119        Self {
120            prompt_host: Some(prompt_host),
121            ..self
122        }
123    }
124
125    /// Supplies the host's [`Stop`]: once it is flipped, every task this
126    /// `Tasks` is driving is abandoned where it stands — the turn in flight
127    /// included, never recorded as an outcome — and left resumable, and every
128    /// wait and ask driving under it returns as timed out. What a server
129    /// shutting down gives the tasks it drives (see [`Stop`]).
130    #[must_use]
131    pub fn with_stop(self, stop: Stop) -> Self {
132        Self {
133            stop: Some(stop),
134            ..self
135        }
136    }
137
138    /// Whether this `Tasks` can currently put an `Approve::Prompt` question
139    /// to whoever answers for it — `false` with no [`PromptHost`] supplied.
140    pub fn can_ask(&self) -> bool {
141        self.prompt_host.as_deref().is_some_and(PromptHost::can_ask)
142    }
143
144    /// The mentra store directory `workspace` resolves to, without minting or
145    /// reading any task.
146    ///
147    /// What a host's attended, one-shot route — no durable task, no handle —
148    /// needs to land its conversation store on the same directory
149    /// [`spawn`](Self::spawn) would use for the same workspace, so the two
150    /// share one conversation history and one memory root rather than
151    /// falling back to two.
152    pub fn store_dir(workspace: &Path) -> Result<PathBuf, Error> {
153        let data = DataDir::discover()
154            .map_err(|error| Error::new(format!("open task data directory: {error}")))?;
155        data.resolve_store_dir(workspace).map_err(Error::new)
156    }
157
158    /// A private directory for one host's own records about this workspace's
159    /// tasks — what an adapter keeps that a task directory does not, such as
160    /// which protocol-level ids it handed out for which handles.
161    ///
162    /// `<data root>/workspaces/<key>/hosts/<host>`, created `0700` on first
163    /// use. `host` is one path component of lowercase ASCII letters, digits,
164    /// and `-`, so a name can never reach outside its own directory. Nothing
165    /// in this crate reads it; deleting it loses the host's index, never a
166    /// task.
167    pub fn host_dir(&self, host: &str) -> Result<PathBuf, Error> {
168        self.data
169            .resolve_host_dir(&self.workspace, host)
170            .map_err(Error::new)
171    }
172
173    fn ctx(&self, live: Option<Arc<dyn LiveSink>>) -> DriveContext {
174        DriveContext::new(live, self.prompt_host.clone()).stopping_on(self.stop.clone())
175    }
176
177    /// Mints a task and returns its handle immediately. Durable and resumable
178    /// from the moment this returns: nothing has attached yet, and nothing
179    /// has to for the handle to be good.
180    pub fn spawn(&self, spec: RunSpec) -> Result<TaskHandle, Error> {
181        let RunSpec {
182            prompt,
183            provider,
184            base_url,
185            model,
186            shell,
187            system_prompt,
188            effort,
189            approve,
190            deadline,
191            tool_budget,
192            token_budget,
193            detached,
194            continuation,
195            hop,
196            not_after_ms,
197        } = spec;
198        if prompt.trim().is_empty() {
199            return Err(Error::new("prompt is empty"));
200        }
201        if prompt.len() > state::MAX_PROMPT {
202            return Err(Error::new(format!(
203                "prompt is {} bytes; the limit is {}",
204                prompt.len(),
205                state::MAX_PROMPT
206            )));
207        }
208        // Refused here, before a task directory is even minted: a task whose
209        // approval mode can never be honored by this `Tasks` — no
210        // `PromptHost`, or one that cannot currently ask — is refused as a
211        // cheaper, clearer failure than one that could never make progress.
212        crate::approve::validate_approval(approve, self.can_ask())?;
213
214        let deadline_ms = duration_ms(deadline.unwrap_or(DEFAULT_DEADLINE));
215        let options = RunOptions {
216            provider,
217            base_url,
218            model,
219            no_shell: !shell,
220            system_prompt,
221            append_system_prompt: None,
222            effort,
223            approve,
224            deadline_ms: Some(deadline_ms),
225            tool_budget,
226            token_budget,
227        };
228
229        let canonical = canonical_workspace(&self.workspace).map_err(|error| {
230            Error::new(format!(
231                "resolve workspace {}: {error}",
232                self.workspace.display()
233            ))
234        })?;
235        let key = self.data.ensure_workspace(&canonical).map_err(Error::new)?;
236
237        // Read off the published BASIS_TASK_ID protocol: a task spawning
238        // another is, by default, that task's parent (ADR-0017's tree).
239        let caller = crate::current_task();
240        if let Some(caller) = &caller
241            && !detached
242            && caller.key() != key
243        {
244            return Err(Error::new(format!(
245                "current task {caller} belongs to another workspace; spawn a detached task to \
246                 start work here"
247            ))
248            .with_hint(Hint::SpawnDetached));
249        }
250        let parent = if detached { None } else { caller };
251
252        // T2(a): resolving which conversation to continue, minting the task
253        // directory, and recording the claim (`continues`) on it are one
254        // unit against a second spawn targeting this same workspace —
255        // otherwise two concurrent `--continue`s could both resolve the same
256        // conversation before either's claim is on disk for the other to
257        // see. Held past `save_meta` below, then dropped explicitly: nothing
258        // after that point reads or writes what this protects.
259        let continue_lock = lock::exclusive(&self.data.continue_lock(&key))
260            .map_err(|error| Error::new(format!("acquire workspace continuation lock: {error}")))?;
261        let continues = self.resolve_continuation(&canonical, &key, continuation)?;
262
263        let requested_deadline = attach::earlier_deadline(
264            Some(
265                state::now_ms()
266                    .checked_add(deadline_ms)
267                    .ok_or_else(|| Error::new("task deadline exceeds the system clock range"))?,
268            ),
269            not_after_ms,
270        );
271        let mut hop = hop;
272        let deadline_at = match &parent {
273            Some(parent_handle) => {
274                let paths = attach::resolve(&self.data, parent_handle.as_str()).map_err(|_| {
275                    Error::new(format!("parent task {parent_handle} does not exist"))
276                })?;
277                let owner = state::load_meta(&paths).map_err(Error::new)?;
278                let accepts = state::read_terminal(&paths).map_err(Error::new)?.is_none()
279                    && owner.pending_terminal.is_none()
280                    && !state::cancel_requested(&paths)
281                    && !owner.deadline_passed();
282                if !accepts {
283                    return Err(Error::new(format!(
284                        "parent task {parent_handle} is no longer running"
285                    )));
286                }
287                // A child is its parent's work one level down in-process:
288                // as many hops from the top-level caller, never fewer.
289                hop = hop.max(owner.hop);
290                attach::earlier_deadline(requested_deadline, owner.deadline_at_ms)
291            }
292            None => requested_deadline,
293        };
294
295        let agents = self.data.agents_dir(&key);
296        let existing = std::fs::read_dir(&agents)
297            .map_err(|error| Error::new(format!("scan workspace agents: {error}")))?
298            .count();
299        if existing >= state::MAX_TASKS {
300            return Err(Error::task_limit(format!(
301                "workspace has {} tasks (the limit); archive old agent directories under {}",
302                state::MAX_TASKS,
303                agents.display()
304            )));
305        }
306
307        // `create_dir` is the atomic claim on the handle; a uuid collision retries.
308        let (task, paths) = loop {
309            let task = format!("{key}/{}", uuid::Uuid::new_v4().simple());
310            let paths = self
311                .data
312                .agent_dir(&task)
313                .expect("a minted handle is well-formed");
314            match std::fs::create_dir(paths.dir()) {
315                Ok(()) => {
316                    data_dir::restrict_directory(paths.dir())
317                        .map_err(|error| Error::new(format!("restrict task directory: {error}")))?;
318                    break (task, paths);
319                }
320                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
321                Err(error) => return Err(Error::new(format!("create task directory: {error}"))),
322            }
323        };
324        let meta = TaskMeta::new(
325            task.clone(),
326            parent.map(|handle| handle.as_str().to_string()),
327            detached,
328            canonical.to_string_lossy().into_owned(),
329            prompt,
330            options,
331            deadline_at,
332        )
333        .continuing(continues)
334        .at_hop(hop);
335        state::save_meta(&paths, &meta).map_err(Error::new)?;
336        drop(continue_lock);
337
338        TaskHandle::parse(task)
339    }
340
341    /// The conversation `continuation` names, when it names one: `New`
342    /// mints, `Latest` picks the conversation this workspace was last worked
343    /// in, `Named` picks a specific one — the same resolution `--continue`
344    /// and `--continue --session <ID>` need.
345    fn resolve_continuation(
346        &self,
347        workspace: &Path,
348        key: &str,
349        continuation: Continuation,
350    ) -> Result<Option<String>, Error> {
351        let requested = match continuation {
352            Continuation::New => return Ok(None),
353            Continuation::Latest => None,
354            Continuation::Named(handle) => Some(handle),
355        };
356        let summaries = tasks::workspace_tasks(&self.data, workspace)
357            .map_err(Error::new)?
358            .unwrap_or_default();
359        let chosen = match &requested {
360            // `named` tells a bad argument (malformed, or another workspace's
361            // handle) apart from a state fact (well-formed, this workspace,
362            // simply not recorded) — the same distinction `Error` carries.
363            Some(handle) => {
364                tasks::named(&summaries, key, handle.as_str()).map_err(|error| match error {
365                    tasks::NamedError::InvalidReference(message) => {
366                        Error::invalid_reference(message)
367                    }
368                    tasks::NamedError::NotFound(message) => Error::new(message),
369                })?
370            }
371            None => tasks::latest_conversation(&summaries).ok_or_else(|| {
372                Error::new("no task in this workspace has a conversation to continue")
373                    .with_hint(Hint::SpawnFresh)
374            })?,
375        };
376        if chosen.state == "running" {
377            return Err(Error::new(format!(
378                "task {} is running; its attach lock is what keeps one conversation to one \
379                 executor",
380                chosen.task
381            ))
382            .with_hint(Hint::Wait(TaskHandle::parse(chosen.task.clone())?)));
383        }
384        if chosen.agent_id.is_empty() {
385            return Err(Error::new(format!(
386                "task {} has no conversation yet: nothing has attached to it",
387                chosen.task
388            ))
389            .with_hint(Hint::Wait(TaskHandle::parse(chosen.task.clone())?)));
390        }
391        // T2(a): a sibling that already recorded `continues` against this
392        // same conversation, and has not yet settled, holds an open claim on
393        // it — minting a second claimant here is exactly the race that lets
394        // two executors resume one conversation at once.
395        if let Some(claimant) =
396            tasks::claimed_continuation(&self.data, key, &chosen.agent_id).map_err(Error::new)?
397        {
398            let claimant = TaskHandle::parse(claimant)?;
399            return Err(Error::new(format!(
400                "task {claimant} already continues this conversation; a conversation admits \
401                 one open claim at a time"
402            ))
403            .with_hint(Hint::Wait(claimant)));
404        }
405        Ok(Some(chosen.agent_id.clone()))
406    }
407
408    /// Enqueues a follow-up turn. Never blocks and never drives: the message
409    /// is durable the moment this returns, and progress happens only once
410    /// something attaches — `ask`, `wait`, or any other attacher.
411    pub fn send(&self, handle: &TaskHandle, message: impl Into<String>) -> Result<String, Error> {
412        let paths = attach::resolve(&self.data, handle.as_str()).map_err(Error::new)?;
413        inbox::enqueue(&paths, handle.as_str(), message.into()).map_err(Error::new)
414    }
415
416    /// Enqueues a follow-up turn and awaits its correlated reply, attaching
417    /// to drive the task whenever the attach lock is free. `send` plus
418    /// [`wait_message`](Self::wait_message), as one call — the edge is
419    /// validated before the enqueue, so a rejected wait cannot leave a
420    /// message behind.
421    ///
422    /// **Threading:** the edge check and the enqueue are this call's own
423    /// synchronous prelude and run through this crate's own `blocking`
424    /// helper; the wait after it is `attach::wait_for_message`'s own.
425    pub async fn ask(
426        &self,
427        handle: &TaskHandle,
428        caller: Option<&TaskHandle>,
429        message: impl Into<String>,
430        timeout: Duration,
431    ) -> Result<Reply, Error> {
432        let data = self.data.clone();
433        let target = handle.clone();
434        let caller = caller.cloned();
435        let message = message.into();
436        let message_id = blocking(move || {
437            policy::validate_wait_edge(
438                &data,
439                caller.as_ref().map(TaskHandle::as_str),
440                target.as_str(),
441            )
442            .map_err(Error::new)?;
443            let paths = attach::resolve(&data, target.as_str()).map_err(Error::new)?;
444            inbox::enqueue(&paths, target.as_str(), message).map_err(Error::new)
445        })
446        .await?;
447        let outcome = attach::wait_for_message(
448            &self.data,
449            handle.as_str(),
450            &message_id,
451            timeout,
452            self.ctx(None),
453        )
454        .await
455        .map_err(Error::new)?;
456        Ok(Reply {
457            message_id,
458            outcome,
459        })
460    }
461
462    /// Awaits one already-enqueued message's correlated reply — the `wait
463    /// --message` shape: repeatable without any policy check once the reply
464    /// exists, and edge-validated only for the wait that has to actually
465    /// happen.
466    ///
467    /// **Threading:** the dispatch check and the edge check are this call's
468    /// own synchronous prelude and run through this crate's own `blocking`
469    /// helper; the wait after it, when one is still needed, is
470    /// `attach::wait_for_message`'s own.
471    pub async fn wait_message(
472        &self,
473        handle: &TaskHandle,
474        caller: Option<&TaskHandle>,
475        message_id: &str,
476        timeout: Duration,
477    ) -> Result<WaitOutcome, Error> {
478        let data = self.data.clone();
479        let target = handle.clone();
480        let caller = caller.cloned();
481        let mid = message_id.to_string();
482        let resolved = blocking(move || -> Result<Option<Value>, Error> {
483            let paths = attach::resolve(&data, target.as_str()).map_err(Error::new)?;
484            let messages = inbox::load(&paths).map_err(Error::new)?;
485            let terminal = state::read_terminal(&paths).map_err(Error::new)?;
486            if let Some(payload) = inbox::message_payload_for_dispatch(
487                target.as_str(),
488                &messages,
489                &mid,
490                terminal.as_ref(),
491            )
492            .map_err(Error::new)?
493            {
494                return Ok(Some(payload));
495            }
496            policy::validate_wait_edge(
497                &data,
498                caller.as_ref().map(TaskHandle::as_str),
499                target.as_str(),
500            )
501            .map_err(Error::new)?;
502            Ok(None)
503        })
504        .await?;
505        match resolved {
506            Some(payload) => Ok(WaitOutcome::Terminal(TerminalRecord::from_raw(payload))),
507            None => attach::wait_for_message(
508                &self.data,
509                handle.as_str(),
510                message_id,
511                timeout,
512                self.ctx(None),
513            )
514            .await
515            .map_err(Error::new),
516        }
517    }
518
519    /// Awaits the task's terminal record, attaching to drive it whenever the
520    /// attach lock is free — repeatable: a settled task's record is read
521    /// straight off disk, never rerun. `live`, when given, is shown every
522    /// event while (and only while) this call is the one driving.
523    ///
524    /// **Threading:** the terminal read and the edge check are this call's
525    /// own synchronous prelude and run through this crate's own `blocking`
526    /// helper; the wait after it, when one is still needed, is this crate's
527    /// own `wait_unvalidated`'s.
528    pub async fn wait(
529        &self,
530        handle: &TaskHandle,
531        caller: Option<&TaskHandle>,
532        timeout: Duration,
533        live: Option<Arc<dyn LiveSink>>,
534    ) -> Result<WaitOutcome, Error> {
535        let data = self.data.clone();
536        let target = handle.clone();
537        let caller = caller.cloned();
538        let resolved = blocking(move || -> Result<Option<Value>, Error> {
539            let paths = attach::resolve(&data, target.as_str()).map_err(Error::new)?;
540            if let Some(terminal) = state::read_terminal(&paths).map_err(Error::new)? {
541                return Ok(Some(terminal));
542            }
543            policy::validate_wait_edge(
544                &data,
545                caller.as_ref().map(TaskHandle::as_str),
546                target.as_str(),
547            )
548            .map_err(Error::new)?;
549            Ok(None)
550        })
551        .await?;
552        match resolved {
553            Some(terminal) => Ok(WaitOutcome::Terminal(TerminalRecord::from_raw(terminal))),
554            None => self.wait_unvalidated(handle, timeout, live).await,
555        }
556    }
557
558    /// [`wait`](Self::wait) minus the edge check — never exposed on its own,
559    /// since any caller could reach it for any handle and there would be
560    /// nothing left of the wait-edge policy. [`spawn_and_wait`](Self::spawn_and_wait)
561    /// is the one legitimate skip: the edge between a call's own caller and
562    /// the task it just minted is exactly the one [`spawn`](Self::spawn)
563    /// established a moment ago (a fresh descendant, or an independent root
564    /// when detached), and re-deriving it through a `caller` a host is free
565    /// to pass differently here would recompute what that call already
566    /// knows — against a value that, if stale, could strand a task nobody
567    /// is left validated to drive.
568    ///
569    /// **Threading:** the terminal read is this call's own synchronous
570    /// prelude and runs through [`blocking`]; the wait after it is
571    /// [`attach::wait_for_terminal`]'s own — see its doc for where every lock
572    /// and fs read *it* makes runs, model turns included.
573    async fn wait_unvalidated(
574        &self,
575        handle: &TaskHandle,
576        timeout: Duration,
577        live: Option<Arc<dyn LiveSink>>,
578    ) -> Result<WaitOutcome, Error> {
579        let data = self.data.clone();
580        let target = handle.clone();
581        let resolved = blocking(move || -> Result<Option<Value>, Error> {
582            let paths = attach::resolve(&data, target.as_str()).map_err(Error::new)?;
583            state::read_terminal(&paths).map_err(Error::new)
584        })
585        .await?;
586        if let Some(terminal) = resolved {
587            return Ok(WaitOutcome::Terminal(TerminalRecord::from_raw(terminal)));
588        }
589        let ctx = self.ctx(live);
590        attach::wait_for_terminal(&self.data, handle.as_str(), timeout, &ctx)
591            .await
592            .map_err(Error::new)
593    }
594
595    /// Mints a task and immediately attaches to drive it to a terminal
596    /// result — `spawn --await`'s shape, and the one place a wait skips edge
597    /// validation: see this crate's private `wait_unvalidated` for why that
598    /// is safe only here.
599    ///
600    /// **Threading:** [`spawn`](Self::spawn) is a synchronous unit in its own
601    /// right — a directory scan, the continuation lock, `create_dir`,
602    /// `save_meta` — and runs through this crate's own `blocking` helper here
603    /// exactly as it would if this crate wrote it as its own
604    /// `blocking`-wrapped prelude; the wait after it is this crate's own
605    /// `wait_unvalidated`'s.
606    pub async fn spawn_and_wait(
607        &self,
608        spec: RunSpec,
609        timeout: Duration,
610        live: Option<Arc<dyn LiveSink>>,
611    ) -> Result<(TaskHandle, WaitOutcome), Error> {
612        let tasks = self.clone();
613        let handle = blocking(move || tasks.spawn(spec)).await?;
614        let outcome = self.wait_unvalidated(&handle, timeout, live).await?;
615        Ok((handle, outcome))
616    }
617
618    /// Whether `caller` (or nobody, for a host outside any task) may
619    /// [`wait`](Self::wait) or [`ask`](Self::ask) `target` — the ownership
620    /// rule ADR-0017 states: a descendant or an independent root is safe, an
621    /// ancestor or a peer is not (send it instead, and read the reply from
622    /// [`inbox`](Self::inbox)). `Err` names which rule the edge breaks; a
623    /// caller that only wants the yes/no can ask for `.is_ok()`.
624    pub fn validate_wait_edge(
625        &self,
626        caller: Option<&TaskHandle>,
627        target: &TaskHandle,
628    ) -> Result<(), Error> {
629        policy::validate_wait_edge(&self.data, caller.map(TaskHandle::as_str), target.as_str())
630            .map_err(Error::new)
631    }
632
633    /// Whether `caller` (or nobody, for a host outside any task) may
634    /// [`cancel`](Self::cancel) `target` — downward-only, ADR-0017's rule:
635    /// itself or a descendant, never an ancestor or a peer. `Err` names which
636    /// rule the target breaks; a caller that wants the refusal to win over an
637    /// idempotent observation of an already-settled target checks this
638    /// first, the way `basis cancel` does.
639    pub fn validate_cancel_target(
640        &self,
641        caller: Option<&TaskHandle>,
642        target: &TaskHandle,
643    ) -> Result<(), Error> {
644        policy::validate_cancel_target(&self.data, caller.map(TaskHandle::as_str), target.as_str())
645            .map_err(Error::new)
646    }
647
648    /// Requests downward cancellation of `target` and every attached,
649    /// non-terminal descendant. Idempotent: cancelling an already-settled
650    /// task is a no-op, and this call never blocks on one settling.
651    pub fn cancel(&self, handle: &TaskHandle, caller: Option<&TaskHandle>) -> Result<(), Error> {
652        // Existence is checked here rather than left to `cancel_tree`, which
653        // silently skips a directory that is not there: a caller cancelling a
654        // handle that never existed should hear about it.
655        attach::resolve(&self.data, handle.as_str()).map_err(Error::new)?;
656        policy::validate_cancel_target(&self.data, caller.map(TaskHandle::as_str), handle.as_str())
657            .map_err(Error::new)?;
658        attach::cancel_tree(&self.data, handle.as_str()).map_err(Error::new)
659    }
660
661    /// Opens a cursor over the task's event journal, replay-from-start. Pure
662    /// observation — this never attaches or drives; poll it in a loop beside
663    /// [`terminal`](Self::terminal) for `basis watch`'s own shape, or just
664    /// long enough to catch up on a run already in progress.
665    pub fn watch(&self, handle: &TaskHandle) -> Result<EventCursor, Error> {
666        let paths = attach::resolve(&self.data, handle.as_str()).map_err(Error::new)?;
667        Ok(EventCursor::new(EventTail::new(&paths, 0)))
668    }
669
670    /// The terminal record, raw and typed side by side, or `None` for a task
671    /// still resumable.
672    /// Repeatable and lock-free: existence of `terminal.json` *is* the
673    /// completion signal (ADR-0019).
674    pub fn terminal(&self, handle: &TaskHandle) -> Result<Option<TerminalRecord>, Error> {
675        let paths = attach::resolve(&self.data, handle.as_str()).map_err(Error::new)?;
676        state::read_terminal(&paths)
677            .map(|record| record.map(TerminalRecord::from_raw))
678            .map_err(Error::new)
679    }
680
681    /// Whether a live executor currently holds the task's attach lock.
682    pub fn is_attached(&self, handle: &TaskHandle) -> Result<bool, Error> {
683        let paths = attach::resolve(&self.data, handle.as_str()).map_err(Error::new)?;
684        Ok(lock::is_held(&paths.attach_lock()))
685    }
686
687    /// Every message accepted on the task's inbox, bounded 4 KiB summaries
688    /// with truncation metadata — the `basis inbox` payload shape.
689    pub fn inbox(&self, handle: &TaskHandle) -> Result<InboxRecord, Error> {
690        let paths = attach::resolve(&self.data, handle.as_str()).map_err(Error::new)?;
691        let messages = inbox::load(&paths).map_err(Error::new)?;
692        Ok(inbox::inbox_record(handle.as_str(), &messages))
693    }
694
695    /// The workspace the task was spawned against, as it was recorded at
696    /// spawn — not necessarily `Tasks::open`'s own workspace, since a handle
697    /// resolves purely from itself.
698    pub fn workspace_of(&self, handle: &TaskHandle) -> Result<PathBuf, Error> {
699        Ok(PathBuf::from(self.meta(handle)?.workspace))
700    }
701
702    /// The agent-to-agent hop the task's work arrived at, as recorded at
703    /// spawn — see [`RunSpec::with_hop`](crate::RunSpec::with_hop).
704    pub fn hop(&self, handle: &TaskHandle) -> Result<u32, Error> {
705        Ok(self.meta(handle)?.hop)
706    }
707
708    /// When the task gives up, in milliseconds since the epoch, as recorded
709    /// at spawn — the instant every turn is bounded by, so a host that hands
710    /// the deadline on (an A2A server telling a caller, say) states the one
711    /// the task actually runs under. `None` for a task with no deadline.
712    pub fn deadline_at_ms(&self, handle: &TaskHandle) -> Result<Option<u64>, Error> {
713        Ok(self.meta(handle)?.deadline_at_ms)
714    }
715
716    fn meta(&self, handle: &TaskHandle) -> Result<state::TaskMeta, Error> {
717        let paths = attach::resolve(&self.data, handle.as_str()).map_err(Error::new)?;
718        state::load_meta(&paths).map_err(Error::new)
719    }
720
721    /// Every task recorded for this `Tasks`'s workspace, last worked in
722    /// first. Empty for a workspace nothing has ever run in — that is a
723    /// complete answer, not an error.
724    pub fn list(&self) -> Result<Vec<TaskSummary>, Error> {
725        Ok(tasks::workspace_tasks(&self.data, &self.workspace)
726            .map_err(Error::new)?
727            .unwrap_or_default())
728    }
729}
730
731fn duration_ms(duration: Duration) -> u64 {
732    duration.as_millis().min(u128::from(u64::MAX)) as u64
733}
734
735/// Runs one bounded, synchronous unit of this crate's own blocking work —
736/// a lock acquisition, an fs read or write, [`Tasks::spawn`]'s own mint — off
737/// the caller's async executor and onto tokio's blocking thread pool (G7's
738/// pattern, `ca9ddcb`, applied at this crate's own boundary).
739///
740/// Every `pub async fn` on [`Tasks`] that has a synchronous prelude (an edge
741/// check, an enqueue, a terminal read, `spawn` itself) runs it through this
742/// rather than inline on the caller's task — see each method's own
743/// `**Threading:**` note for which part that is. [`attach::wait_for_terminal`]
744/// and [`attach::wait_for_message`] carry the other half of the same rule for
745/// the poll loop and the model turns it drives.
746async fn blocking<T, F>(work: F) -> Result<T, Error>
747where
748    F: FnOnce() -> Result<T, Error> + Send + 'static,
749    T: Send + 'static,
750{
751    tokio::task::spawn_blocking(work)
752        .await
753        .unwrap_or_else(|error| Err(Error::new(format!("background task failed: {error}"))))
754}
755
756#[cfg(test)]
757mod tests {
758    use super::*;
759    use crate::Approve;
760
761    fn tasks() -> (tempfile::TempDir, tempfile::TempDir, Tasks) {
762        let data_dir = tempfile::tempdir().unwrap();
763        let workspace = tempfile::tempdir().unwrap();
764        let tasks = Tasks::open_at(data_dir.path(), workspace.path()).unwrap();
765        (data_dir, workspace, tasks)
766    }
767
768    /// The general hazard `spawn_and_wait` exists to route around: an
769    /// ordinary `wait` refuses a caller that does not exist to validate the
770    /// edge against — the shape a stale `BASIS_TASK_ID` takes once its own
771    /// task directory is gone (archived, or simply never real).
772    #[tokio::test]
773    async fn wait_refuses_a_caller_that_does_not_exist() {
774        let (_data_dir, _workspace, tasks) = tasks();
775        let stale_caller = TaskHandle::parse(format!("{:016x}/{:032x}", 1, 1)).unwrap();
776        let handle = tasks
777            .spawn(
778                RunSpec::new("hello")
779                    .with_approve(Approve::Always)
780                    .detached(),
781            )
782            .expect("spawns");
783
784        let refused = tasks
785            .wait(&handle, Some(&stale_caller), Duration::from_secs(1), None)
786            .await
787            .expect_err("a caller that does not exist cannot be validated against");
788        assert!(refused.to_string().contains("does not exist"), "{refused}");
789    }
790
791    /// `spawn_and_wait` never asks the wait-edge question at all, so a stale
792    /// `BASIS_TASK_ID` — one naming a caller task that no longer exists —
793    /// cannot strand the task this same call just minted, the way routing a
794    /// `spawn --await` through the ordinary edge-validated `wait` used to.
795    #[tokio::test]
796    async fn spawn_and_wait_does_not_edge_validate_the_task_it_just_minted() {
797        let (_data_dir, _workspace, tasks) = tasks();
798        // A deadline so tight it has certainly passed by the time the attach
799        // that follows runs: `run_model` bails on it before ever opening a
800        // workspace or touching a provider, which is what keeps this test
801        // fast and network-free while still exercising a real attach.
802        let spec = RunSpec::new("hello")
803            .with_approve(Approve::Always)
804            .with_deadline(Duration::from_nanos(1))
805            .detached();
806
807        let (_handle, outcome) = tasks
808            .spawn_and_wait(spec, Duration::from_secs(5), None)
809            .await
810            .expect("spawn_and_wait never asks the wait-edge question at all");
811        let WaitOutcome::Terminal(payload) = outcome else {
812            panic!("a tight deadline settles immediately rather than timing the wait out");
813        };
814        assert_eq!(payload.raw["state"], "failed");
815        assert_eq!(payload.stopped_by, Some(basis::Bound::Deadline));
816    }
817
818    /// `Approve::Prompt` names a question nobody can answer without a
819    /// `PromptHost`; a `Tasks` with none refuses it at spawn, before a task
820    /// directory even exists, rather than minting one that could never make
821    /// progress — the doc on [`crate::Approve::Prompt`] promises exactly
822    /// this.
823    #[test]
824    fn spawn_refuses_prompt_mode_with_no_prompt_host() {
825        let (_data_dir, _workspace, tasks) = tasks();
826
827        let error = tasks
828            .spawn(RunSpec::new("hello").with_approve(Approve::Prompt))
829            .expect_err("no PromptHost means Prompt can never be answered");
830        assert!(error.to_string().contains("ask"), "{error}");
831    }
832
833    /// `is_attached` is documented as a read, and `list` asks the same
834    /// question of every task it reports. A read that leaves a file behind is
835    /// not one: probing a task nothing has ever attached must find no lock
836    /// and mint none, so a listing of a workspace is not also a write to
837    /// every task directory in it.
838    #[test]
839    fn probing_attachment_does_not_mint_the_lock_file() {
840        let (_data_dir, _workspace, tasks) = tasks();
841        let handle = tasks
842            .spawn(
843                RunSpec::new("hello")
844                    .with_approve(Approve::Always)
845                    .detached(),
846            )
847            .expect("spawns");
848        let paths = attach::resolve(&tasks.data, handle.as_str()).expect("agent dir");
849        assert!(
850            !paths.attach_lock().exists(),
851            "a task nothing has attached starts with no lock file"
852        );
853
854        assert!(!tasks.is_attached(&handle).expect("probes"));
855        let listed = tasks.list().expect("lists");
856        assert!(listed.iter().any(|task| task.task == handle.as_str()));
857
858        assert!(
859            !paths.attach_lock().exists(),
860            "observing a task must leave its directory as it found it"
861        );
862    }
863
864    /// T3: `wait`'s own lock and fs work — the poll loop's `resolve`,
865    /// `read_terminal`, `try_attach`, all of it — runs off the tokio worker
866    /// thread this test's (deliberately single-threaded) executor is. A
867    /// concurrent, purely async ticker sharing that one worker keeps making
868    /// progress the whole time `wait`'s poll loop sees a contended attach
869    /// lock, which a `wait` running any of that work inline could not
870    /// guarantee: a `current_thread` runtime has exactly one worker, and
871    /// blocking it stalls everything else scheduled there.
872    #[tokio::test(flavor = "current_thread")]
873    async fn wait_does_not_block_the_executor_it_is_called_from() {
874        let (_data_dir, _workspace, tasks) = tasks();
875        let handle = tasks
876            .spawn(
877                RunSpec::new("hello")
878                    .with_approve(Approve::Always)
879                    // Fails fast, without a network call, the moment it is
880                    // actually driven — this test's own point is entirely
881                    // about the poll loop leading up to that, not the turn.
882                    .with_provider("not-a-provider"),
883            )
884            .expect("spawns");
885        let paths = attach::resolve(&tasks.data, handle.as_str()).expect("agent dir");
886        // Stands in for another process already driving the task: `wait`'s
887        // poll loop sees a contended attach lock every iteration for a
888        // controlled stretch.
889        let held = attach::try_attach(&paths).unwrap().expect("lock is free");
890
891        let ticks = Arc::new(std::sync::atomic::AtomicUsize::new(0));
892        let counter = Arc::clone(&ticks);
893        let ticker = async move {
894            for _ in 0..40 {
895                tokio::time::sleep(Duration::from_millis(5)).await;
896                counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
897            }
898        };
899        let releaser = async {
900            tokio::time::sleep(Duration::from_millis(200)).await;
901            drop(held);
902        };
903        let waiter = tasks.wait(&handle, None, Duration::from_secs(5), None);
904        let (outcome, (), ()) = tokio::join!(waiter, ticker, releaser);
905        outcome.expect("wait completes once the lock frees");
906        assert!(
907            ticks.load(std::sync::atomic::Ordering::SeqCst) >= 30,
908            "a ticker sharing this runtime's one worker thread kept making \
909             progress while wait's poll loop was contended — proof that \
910             loop's lock probes and fs reads never held that thread"
911        );
912    }
913
914    /// T2(a): a task minted with `continues = Some(agent_id)` holds an open
915    /// claim on that conversation until it settles — a second spawn that
916    /// would continue the same conversation refuses rather than mint a
917    /// second claimant, the double-continuation race `continue_lock` and
918    /// this check exist to close.
919    #[test]
920    fn a_second_continuation_of_the_same_conversation_is_refused_while_the_first_is_open() {
921        let (_data_dir, _workspace, tasks) = tasks();
922
923        // Stand in for a task that finished with a conversation to
924        // continue — built directly, the way `attach`'s own tests build a
925        // completed task, rather than driven through a real model.
926        let done = tasks
927            .spawn(RunSpec::new("hello").with_approve(Approve::Always))
928            .expect("spawns");
929        let paths = attach::resolve(&tasks.data, done.as_str()).expect("agent dir");
930        let mut meta = state::load_meta(&paths).expect("meta.json");
931        meta.agent_id = "conversation-1".to_string();
932        state::save_meta(&paths, &meta).expect("save");
933        state::write_terminal(
934            &paths,
935            &serde_json::json!({"state": "succeeded", "result": "d"}),
936        )
937        .expect("terminal");
938
939        let first = tasks
940            .spawn(
941                RunSpec::new("step two")
942                    .with_approve(Approve::Always)
943                    .continuing(crate::Continuation::Latest),
944            )
945            .expect("the first continuation claims the conversation");
946
947        let refused = tasks
948            .spawn(
949                RunSpec::new("step two, again")
950                    .with_approve(Approve::Always)
951                    .continuing(crate::Continuation::Latest),
952            )
953            .expect_err("a second, still-open claim on the same conversation is refused");
954        assert!(refused.to_string().contains(first.as_str()), "{refused}");
955
956        // Once the first claimant settles, its claim releases and a fresh
957        // continuation of the same conversation is ordinary again.
958        let first_paths = attach::resolve(&tasks.data, first.as_str()).expect("agent dir");
959        state::write_terminal(
960            &first_paths,
961            &serde_json::json!({"state": "succeeded", "result": "d2"}),
962        )
963        .expect("terminal");
964        tasks
965            .spawn(
966                RunSpec::new("step three")
967                    .with_approve(Approve::Always)
968                    .continuing(crate::Continuation::Latest),
969            )
970            .expect("a settled claimant no longer blocks the conversation");
971    }
972
973    /// ADR-0019: an unattended task always gets a finite service bound, even
974    /// when the caller named none — `attach::run_model` enforces deadlines
975    /// for agents nobody attached to in time, and that has nothing to bound
976    /// against without this.
977    #[test]
978    fn an_unset_deadline_records_the_default_at_spawn() {
979        let (_data_dir, _workspace, tasks) = tasks();
980
981        let handle = tasks
982            .spawn(RunSpec::new("hello").with_approve(Approve::Always))
983            .expect("spawns");
984
985        // Grey-box: `Tasks` exposes no deadline accessor — the durable
986        // record is basis-tasks's own business — so the test reads it the
987        // way `attach`'s own tests read `meta.json` directly.
988        let paths = attach::resolve(&tasks.data, handle.as_str()).expect("agent dir");
989        let meta = state::load_meta(&paths).expect("meta.json");
990        assert_eq!(
991            meta.options.deadline_ms,
992            Some(duration_ms(DEFAULT_DEADLINE))
993        );
994        assert!(
995            meta.deadline_at_ms.is_some(),
996            "an unattended task always gets a finite service bound"
997        );
998    }
999}