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