1#[cfg(test)]
3mod lifetime_tests;
4mod observe;
5mod result;
6mod watch;
7mod worker;
8use crate::{
9 process,
10 project::{VerifyOptions, selection::Selection},
11 store::{self, Receipts},
12 types::{FailureCode, RequestKey, RunId},
13};
14pub(crate) use observe::saved_state;
15pub use observe::{
16 Counts, RunObservation, State, reconcile_interrupted, status, view, wait, wait_observing,
17};
18pub use result::{
19 Finding, PAGE_SIZE as RESULT_PAGE_SIZE, ResultCursor, ResultState, RunResultPage, RunVerdict,
20 result,
21};
22use serde::{Deserialize, Serialize};
23use std::path::{Path, PathBuf};
24pub use watch::{RunEvent, watch};
25#[doc(hidden)]
26pub use worker::{execute, supervise, supervise_observing_launch};
27
28#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(default)]
31pub struct RunModes {
32 pub speculate: bool,
33}
34impl RunModes {
35 pub(crate) fn is_default(&self) -> bool {
36 self == &Self::default()
37 }
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum Activity {
43 Preparing,
44 Executing,
45 Publishing,
46 Waiting,
47 Cancelling,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(tag = "state", rename_all = "snake_case")]
52pub enum Worker {
53 Starting {
54 launcher: process::ChildIdentity,
55 },
56 Admitted {
57 owner: process::ChildIdentity,
58 },
59 Legacy,
61}
62#[derive(Debug, Clone, Serialize, Deserialize)]
63#[serde(from = "ControlWire", into = "ControlWire")]
64pub struct Control {
65 pub worker: Worker,
66 pub supervisor: Option<process::ChildIdentity>,
68 pub activity: Activity,
69 pub failure_code: Option<FailureCode>,
70}
71
72#[derive(Serialize, Deserialize)]
73#[serde(rename_all = "camelCase")]
74struct ControlWire {
75 worker: Worker,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 supervisor: Option<process::ChildIdentity>,
78 activity: Activity,
79 #[serde(default)]
80 cancellation_requested: bool,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 failure_code: Option<FailureCode>,
83}
84
85impl From<ControlWire> for Control {
86 fn from(wire: ControlWire) -> Self {
87 Self {
88 worker: wire.worker,
89 supervisor: wire.supervisor,
90 activity: if wire.cancellation_requested {
91 Activity::Cancelling
92 } else {
93 wire.activity
94 },
95 failure_code: wire.failure_code,
96 }
97 }
98}
99
100impl From<Control> for ControlWire {
101 fn from(control: Control) -> Self {
102 Self {
103 worker: control.worker,
104 supervisor: control.supervisor,
105 activity: control.activity,
106 cancellation_requested: control.is_cancelling(),
107 failure_code: control.failure_code,
108 }
109 }
110}
111
112impl Control {
113 pub fn is_cancelling(&self) -> bool {
114 self.activity == Activity::Cancelling
115 }
116
117 pub(crate) fn starting() -> Result<Self, String> {
118 Ok(Self {
119 worker: Worker::Starting {
120 launcher: process::child_identity(std::process::id()).map_err(|e| e.to_string())?,
121 },
122 supervisor: None,
123 activity: Activity::Preparing,
124 failure_code: None,
125 })
126 }
127 pub(crate) fn legacy() -> Self {
128 Self {
129 worker: Worker::Legacy,
130 supervisor: None,
131 activity: Activity::Executing,
132 failure_code: None,
133 }
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(
140 tag = "kind",
141 rename_all = "camelCase",
142 rename_all_fields = "camelCase"
143)]
144pub enum Origin {
145 Cli,
146 Mcp,
147 Chat {
148 session_id: crate::types::SessionId,
149 title: String,
150 },
151}
152
153#[derive(Debug, Clone)]
155pub struct Context {
156 pub(crate) repo: PathBuf,
157 pub(crate) state: PathBuf,
158 executable: PathBuf,
159 origin: Origin,
160}
161impl Context {
162 pub fn repo(&self) -> &Path {
164 &self.repo
165 }
166
167 pub(crate) fn executable(&self) -> &Path {
168 &self.executable
169 }
170
171 pub fn state(&self) -> &Path {
173 &self.state
174 }
175
176 pub fn new(repo: &Path, state: Option<&Path>, executable: &Path) -> Result<Self, String> {
177 Ok(Self {
178 repo: crate::workspace::canonical_target(repo).map_err(|e| e.to_string())?,
179 state: crate::workspace::canonical_target(&store::state_dir(state)?)
180 .map_err(|e| e.to_string())?,
181 executable: executable.to_path_buf(),
182 origin: Origin::Cli,
183 })
184 }
185 #[must_use]
187 pub fn with_origin(self, origin: Origin) -> Self {
188 Self { origin, ..self }
189 }
190
191 pub fn discover(repo: &Path, state: Option<&Path>) -> Result<Self, String> {
193 let executable = process::artifactize_executable()?;
194 Self::new(repo, state, &executable)
195 }
196}
197
198pub async fn start(
199 context: &Context,
200 selection: &Selection,
201 options: &VerifyOptions,
202 request_key: Option<RequestKey>,
203) -> Result<RunObservation, String> {
204 start_observing_launch(context, selection, options, request_key, |_, _| {}).await
205}
206
207#[doc(hidden)]
209pub async fn start_observing_launch(
210 context: &Context,
211 selection: &Selection,
212 options: &VerifyOptions,
213 request_key: Option<RequestKey>,
214 launched: impl FnOnce(&RunId, process::ChildIdentity),
215) -> Result<RunObservation, String> {
216 if let Some(key) = &request_key
218 && crate::platform::paths::target_is_file(&context.state.join(store::DATABASE))
219 {
220 let receipts = Receipts::open(&context.state, &context.repo).await?;
221 let result = receipts.keyed_run(&context.repo, key).await;
222 let closed = receipts.close().await;
223 if let Some(id) = result.and_then(|id| closed.map(|()| id))? {
224 return status(context, &id).await;
225 }
226 }
227 let (id, accepted) = crate::project::verify::reserve(
228 &context.repo,
229 Some(&context.state),
230 selection,
231 options,
232 request_key.as_ref(),
233 &context.origin,
234 )
235 .await?;
236 if accepted {
237 let receipts = Receipts::open(&context.state, &context.repo).await?;
238 let result = async {
239 let launch =
240 process::launch_run(&context.executable, &id, &context.repo, &context.state);
241 let admitted = match launch {
242 Ok(identity) => {
243 launched(&id, identity);
244 receipts.admit(&id, identity).await
245 }
246 Err(error) => Err(error.to_string()),
247 };
248 if let Err(error) = admitted {
249 worker::fail(&receipts, &id, FailureCode::SpawnFailed, error.clone()).await?;
250 return Err(format!("Run {id} handoff failed: {error}"));
251 }
252 Ok(())
253 }
254 .await;
255 let closed = receipts.close().await;
256 result.and(closed)?;
257 }
258 crate::platform::release_free_memory();
261 status(context, &id).await
262}
263
264#[derive(Debug, Clone, Serialize)]
265pub struct CancelAcknowledgement {
266 pub run: RunId,
267 pub state: State,
268 pub cancellation_requested: bool,
269}
270pub async fn cancel(context: &Context, id: &RunId) -> Result<CancelAcknowledgement, String> {
271 let current = status(context, id).await?;
273 let receipts = Receipts::open(&context.state, &context.repo).await?;
274 let result = receipts.request_cancel(id).await;
275 let closed = receipts.close().await;
276 let (saved, control) = result.and_then(|saved| closed.map(|()| saved))?;
277 Ok(CancelAcknowledgement {
278 run: id.clone(),
279 state: observe::state_for(saved, control.as_ref(), ¤t.counts),
280 cancellation_requested: control.as_ref().is_some_and(Control::is_cancelling),
281 })
282}
283
284fn owner_died(status: crate::types::RunStatus, control: Option<&Control>) -> Result<bool, String> {
285 if !status.is_open() {
286 return Ok(false);
287 }
288 let owner = control.and_then(|control| match control.worker {
289 Worker::Starting { launcher } => Some(launcher),
290 Worker::Admitted { owner } => Some(owner),
291 Worker::Legacy => None,
292 });
293 Ok(owner.is_some() && !process::is_alive(owner).map_err(|error| error.to_string())?)
294}
295
296pub(crate) async fn reconcile(
297 state: &Path,
298 view: store::RunView,
299) -> Result<store::RunView, String> {
300 if owner_died(view.run.status(), view.run.control.as_ref())? {
301 worker::recover(state, &view).await?;
302 return store::read_run(state, &view.run.id).await;
303 }
304 Ok(view)
305}