1mod follow;
3#[cfg(test)]
4#[path = "tests/lifetime.rs"]
5mod lifetime_tests;
6mod observe;
7mod reference;
8mod result;
9mod summary;
10mod watch;
11mod worker;
12pub use crate::store::{RunSummary, RunView};
13use crate::{
14 process,
15 project::{VerifyOptions, selection::Selection},
16 store::{self, Receipts},
17 types::{FailureCode, RequestKey, RunId},
18};
19pub use follow::{Follow, FollowUpdate, RunFinished, reconcile_open, workspaces};
20pub use observe::{
21 Counts, RunObservation, State, reconcile_interrupted, status, view, wait, wait_for_change,
22 wait_observing,
23};
24pub use reference::{Reference, reference};
25pub use result::{
26 Completion, Finding, PAGE_SIZE as RESULT_PAGE_SIZE, ResultCursor, ResultState, RunResultPage,
27 RunVerdict, Signoff, completion, result,
28};
29use serde::{Deserialize, Serialize};
30use std::path::{Path, PathBuf};
31pub use summary::{
32 Action, ActionRequest, ActionStatus, ActionWaitBound, INLINE_WAIT_SECONDS, RunActionSummary,
33 SignoffStatus, WaitingSignoff, summary, wait_for_action,
34};
35pub use watch::{RunEvent, watch};
36#[doc(hidden)]
37pub use worker::{execute, supervise, supervise_observing_launch};
38
39pub async fn list(
41 state: &Path,
42 repo: Option<&Path>,
43 limit: u32,
44 offset: u32,
45) -> Result<Vec<RunSummary>, String> {
46 store::read_runs(state, repo, limit, offset).await
47}
48
49#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(default, rename_all = "camelCase")]
52pub struct RunModes {
53 pub speculate: bool,
55 #[serde(skip_serializing_if = "std::ops::Not::not")]
58 pub ignore_gates: bool,
59}
60impl RunModes {
61 pub(crate) fn is_default(&self) -> bool {
62 self == &Self::default()
63 }
64
65 pub(crate) fn gating(&self) -> crate::graph::Gating {
67 crate::graph::Gating {
68 errors_block: self.speculate,
69 ignore_dependencies: self.ignore_gates,
70 }
71 }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "snake_case")]
76pub enum Activity {
77 Preparing,
78 Executing,
79 Publishing,
80 Waiting,
81 Cancelling,
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(tag = "state", rename_all = "snake_case")]
86pub enum Worker {
87 Starting {
88 launcher: process::ChildIdentity,
89 },
90 Admitted {
91 owner: process::ChildIdentity,
92 },
93 Legacy,
95}
96#[derive(Debug, Clone, Serialize, Deserialize)]
97#[serde(from = "ControlWire", into = "ControlWire")]
98pub struct Control {
99 pub worker: Worker,
100 pub supervisor: Option<process::ChildIdentity>,
102 pub activity: Activity,
103 pub(crate) only_signoffs: bool,
105 pub failure_code: Option<FailureCode>,
106}
107
108#[derive(Serialize, Deserialize)]
109#[serde(rename_all = "camelCase")]
110struct ControlWire {
111 worker: Worker,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 supervisor: Option<process::ChildIdentity>,
114 activity: Activity,
115 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
116 only_signoffs: bool,
117 #[serde(default)]
118 cancellation_requested: bool,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
120 failure_code: Option<FailureCode>,
121}
122
123impl From<ControlWire> for Control {
124 fn from(wire: ControlWire) -> Self {
125 Self {
126 worker: wire.worker,
127 supervisor: wire.supervisor,
128 activity: if wire.cancellation_requested {
129 Activity::Cancelling
130 } else {
131 wire.activity
132 },
133 failure_code: wire.failure_code,
134 only_signoffs: wire.only_signoffs,
135 }
136 }
137}
138
139impl From<Control> for ControlWire {
140 fn from(control: Control) -> Self {
141 Self {
142 worker: control.worker,
143 supervisor: control.supervisor,
144 activity: control.activity,
145 only_signoffs: control.only_signoffs,
146 cancellation_requested: control.is_cancelling(),
147 failure_code: control.failure_code,
148 }
149 }
150}
151
152impl Control {
153 pub fn is_cancelling(&self) -> bool {
154 self.activity == Activity::Cancelling
155 }
156
157 pub(crate) fn starting() -> Result<Self, String> {
158 Ok(Self {
159 worker: Worker::Starting {
160 launcher: process::child_identity(std::process::id()).map_err(|e| e.to_string())?,
161 },
162 supervisor: None,
163 activity: Activity::Preparing,
164 failure_code: None,
165 only_signoffs: false,
166 })
167 }
168 pub(crate) fn legacy() -> Self {
169 Self {
170 worker: Worker::Legacy,
171 supervisor: None,
172 activity: Activity::Executing,
173 failure_code: None,
174 only_signoffs: false,
175 }
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(
182 tag = "kind",
183 rename_all = "camelCase",
184 rename_all_fields = "camelCase"
185)]
186pub enum Origin {
187 Cli,
188 Mcp,
189 #[serde(other)]
190 Unknown,
191}
192
193#[derive(Debug, Clone)]
195pub struct Context {
196 pub(crate) repo: PathBuf,
197 pub(crate) state: PathBuf,
198 executable: PathBuf,
199 origin: Origin,
200}
201impl Context {
202 pub fn repo(&self) -> &Path {
204 &self.repo
205 }
206
207 pub fn state(&self) -> &Path {
209 &self.state
210 }
211
212 pub fn new(repo: &Path, state: Option<&Path>, executable: &Path) -> Result<Self, String> {
213 Ok(Self {
214 repo: crate::workspace::canonical_target(repo).map_err(|e| e.to_string())?,
215 state: crate::workspace::canonical_target(&store::state_dir(state)?)
216 .map_err(|e| e.to_string())?,
217 executable: executable.to_path_buf(),
218 origin: Origin::Cli,
219 })
220 }
221 pub async fn for_run(
223 state: Option<&Path>,
224 id: &RunId,
225 executable: &Path,
226 ) -> Result<Self, String> {
227 let state = crate::store::state_dir(state)?;
228 let repo = crate::store::read_run_repo(&state, id).await?;
229 Self::new(&repo, Some(&state), executable)
230 }
231
232 pub fn worker_diagnostics(&self, id: &RunId) -> String {
234 crate::process::run_worker_diagnostics(&self.state, id)
235 }
236
237 #[must_use]
239 pub fn with_origin(self, origin: Origin) -> Self {
240 Self { origin, ..self }
241 }
242
243 pub fn discover(repo: &Path, state: Option<&Path>) -> Result<Self, String> {
245 let executable = process::artifactize_executable()?;
246 Self::new(repo, state, &executable)
247 }
248}
249
250pub fn check_eval_backend(
254 backend: &crate::config::Backend,
255 state: Option<&Path>,
256 repo: Option<&Path>,
257) -> Result<(), crate::agent::error::Failure> {
258 backend.admit(|name| {
259 let providers = crate::auth::providers::list(state, repo)?;
260 Ok(providers.custom.contains_key(name.as_str()))
261 })
262}
263
264pub async fn start(
265 context: &Context,
266 selection: &Selection,
267 options: &VerifyOptions,
268 request_key: Option<RequestKey>,
269) -> Result<RunObservation, String> {
270 start_with_args_hash(context, selection, options, request_key, None).await
271}
272
273pub(crate) async fn start_with_args_hash(
275 context: &Context,
276 selection: &Selection,
277 options: &VerifyOptions,
278 request_key: Option<RequestKey>,
279 request_args_hash: Option<String>,
280) -> Result<RunObservation, String> {
281 start_observing_launch_with_hash(
282 context,
283 selection,
284 options,
285 request_key,
286 request_args_hash,
287 |_, _| {},
288 )
289 .await
290}
291
292#[doc(hidden)]
294pub async fn start_observing_launch(
295 context: &Context,
296 selection: &Selection,
297 options: &VerifyOptions,
298 request_key: Option<RequestKey>,
299 launched: impl FnOnce(&RunId, process::ChildIdentity),
300) -> Result<RunObservation, String> {
301 start_observing_launch_with_hash(context, selection, options, request_key, None, launched).await
302}
303
304async fn start_observing_launch_with_hash(
305 context: &Context,
306 selection: &Selection,
307 options: &VerifyOptions,
308 request_key: Option<RequestKey>,
309 request_args_hash: Option<String>,
310 launched: impl FnOnce(&RunId, process::ChildIdentity),
311) -> Result<RunObservation, String> {
312 if let Some(key) = &request_key
314 && crate::platform::paths::target_is_file(&context.state.join(store::DATABASE))
315 {
316 let receipts = Receipts::open(&context.state, &context.repo).await?;
317 let result = receipts
318 .keyed_run(&context.repo, key, request_args_hash.as_deref())
319 .await;
320 let closed = receipts.close().await;
321 if let Some(id) = result.and_then(|id| closed.map(|()| id))? {
322 return status(context, &id).await;
323 }
324 }
325 let (id, accepted) = crate::project::verify::reserve(
326 &context.repo,
327 Some(&context.state),
328 selection,
329 options,
330 request_key.as_ref(),
331 request_args_hash.as_deref(),
332 &context.origin,
333 )
334 .await?;
335 if accepted {
336 let receipts = Receipts::open(&context.state, &context.repo).await?;
337 let result = async {
338 let launch =
339 process::launch_run(&context.executable, &id, &context.repo, &context.state);
340 let admitted = match launch {
341 Ok(identity) => {
342 launched(&id, identity);
343 receipts.admit(&id, identity).await
344 }
345 Err(error) => Err(error.to_string()),
346 };
347 if let Err(error) = admitted {
348 worker::fail(&receipts, &id, FailureCode::SpawnFailed, error.clone()).await?;
349 return Err(format!("Run {id} handoff failed: {error}"));
350 }
351 Ok(())
352 }
353 .await;
354 let closed = receipts.close().await;
355 result.and(closed)?;
356 }
357 crate::platform::release_free_memory();
360 status(context, &id).await
361}
362
363#[derive(Debug, Clone, Serialize)]
364pub struct CancelAcknowledgement {
365 pub run: RunId,
366 pub state: State,
367 pub cancellation_requested: bool,
368}
369pub async fn cancel(context: &Context, id: &RunId) -> Result<CancelAcknowledgement, String> {
370 let current = status(context, id).await?;
372 let receipts = Receipts::open(&context.state, &context.repo).await?;
373 let result = receipts.request_cancel(id).await;
374 let closed = receipts.close().await;
375 let (saved, control) = result.and_then(|saved| closed.map(|()| saved))?;
376 Ok(CancelAcknowledgement {
377 run: id.clone(),
378 state: observe::state_for(saved, control.as_ref(), ¤t.counts),
379 cancellation_requested: control.as_ref().is_some_and(Control::is_cancelling),
380 })
381}
382
383fn owner_died(status: crate::types::RunStatus, control: Option<&Control>) -> Result<bool, String> {
384 if !status.is_open() {
385 return Ok(false);
386 }
387 let owner = control.and_then(|control| match control.worker {
388 Worker::Starting { launcher } => Some(launcher),
389 Worker::Admitted { owner } => Some(owner),
390 Worker::Legacy => None,
391 });
392 Ok(owner.is_some() && !process::is_alive(owner).map_err(|error| error.to_string())?)
393}
394
395pub(crate) async fn reconcile(
396 state: &Path,
397 view: store::RunView,
398) -> Result<store::RunView, String> {
399 if owner_died(view.run.status(), view.run.control.as_ref())? {
400 worker::recover(state, &view).await?;
401 return store::read_run(state, &view.run.id).await;
402 }
403 Ok(view)
404}