Skip to main content

artifactize_core/runs/
mod.rs

1//! Artifactize-owned verification: durable submission, observation and explicit cancellation.
2mod 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
39/// Page saved Runs from one workspace, or all workspaces in this state.
40pub 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/// Per-Run execution modes. Future modes extend this type, not transport signatures.
50#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(default)]
52pub struct RunModes {
53    pub speculate: bool,
54}
55impl RunModes {
56    pub(crate) fn is_default(&self) -> bool {
57        self == &Self::default()
58    }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "snake_case")]
63pub enum Activity {
64    Preparing,
65    Executing,
66    Publishing,
67    Waiting,
68    Cancelling,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(tag = "state", rename_all = "snake_case")]
73pub enum Worker {
74    Starting {
75        launcher: process::ChildIdentity,
76    },
77    Admitted {
78        owner: process::ChildIdentity,
79    },
80    /// Old records have no worker identity and are not evidence of owner death.
81    Legacy,
82}
83#[derive(Debug, Clone, Serialize, Deserialize)]
84#[serde(from = "ControlWire", into = "ControlWire")]
85pub struct Control {
86    pub worker: Worker,
87    /// The supervisor keeps worker files open until its executor has exited and been checked.
88    pub supervisor: Option<process::ChildIdentity>,
89    pub activity: Activity,
90    /// The scheduler has reached its sign-off idle grace, not a machine admission wait.
91    pub(crate) only_signoffs: bool,
92    pub failure_code: Option<FailureCode>,
93}
94
95#[derive(Serialize, Deserialize)]
96#[serde(rename_all = "camelCase")]
97struct ControlWire {
98    worker: Worker,
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    supervisor: Option<process::ChildIdentity>,
101    activity: Activity,
102    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
103    only_signoffs: bool,
104    #[serde(default)]
105    cancellation_requested: bool,
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    failure_code: Option<FailureCode>,
108}
109
110impl From<ControlWire> for Control {
111    fn from(wire: ControlWire) -> Self {
112        Self {
113            worker: wire.worker,
114            supervisor: wire.supervisor,
115            activity: if wire.cancellation_requested {
116                Activity::Cancelling
117            } else {
118                wire.activity
119            },
120            failure_code: wire.failure_code,
121            only_signoffs: wire.only_signoffs,
122        }
123    }
124}
125
126impl From<Control> for ControlWire {
127    fn from(control: Control) -> Self {
128        Self {
129            worker: control.worker,
130            supervisor: control.supervisor,
131            activity: control.activity,
132            only_signoffs: control.only_signoffs,
133            cancellation_requested: control.is_cancelling(),
134            failure_code: control.failure_code,
135        }
136    }
137}
138
139impl Control {
140    pub fn is_cancelling(&self) -> bool {
141        self.activity == Activity::Cancelling
142    }
143
144    pub(crate) fn starting() -> Result<Self, String> {
145        Ok(Self {
146            worker: Worker::Starting {
147                launcher: process::child_identity(std::process::id()).map_err(|e| e.to_string())?,
148            },
149            supervisor: None,
150            activity: Activity::Preparing,
151            failure_code: None,
152            only_signoffs: false,
153        })
154    }
155    pub(crate) fn legacy() -> Self {
156        Self {
157            worker: Worker::Legacy,
158            supervisor: None,
159            activity: Activity::Executing,
160            failure_code: None,
161            only_signoffs: false,
162        }
163    }
164}
165
166/// The surface that accepted a new Run. Old receipts have no known origin.
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(
169    tag = "kind",
170    rename_all = "camelCase",
171    rename_all_fields = "camelCase"
172)]
173pub enum Origin {
174    Cli,
175    Mcp,
176    #[serde(other)]
177    Unknown,
178}
179
180/// Bound repository/state and trusted executable, resolved once by the interface at startup.
181#[derive(Debug, Clone)]
182pub struct Context {
183    pub(crate) repo: PathBuf,
184    pub(crate) state: PathBuf,
185    executable: PathBuf,
186    origin: Origin,
187}
188impl Context {
189    /// The canonical repository this endpoint serves.
190    pub fn repo(&self) -> &Path {
191        &self.repo
192    }
193
194    /// The canonical state directory shared by this endpoint and its Run workers.
195    pub fn state(&self) -> &Path {
196        &self.state
197    }
198
199    pub fn new(repo: &Path, state: Option<&Path>, executable: &Path) -> Result<Self, String> {
200        Ok(Self {
201            repo: crate::workspace::canonical_target(repo).map_err(|e| e.to_string())?,
202            state: crate::workspace::canonical_target(&store::state_dir(state)?)
203                .map_err(|e| e.to_string())?,
204            executable: executable.to_path_buf(),
205            origin: Origin::Cli,
206        })
207    }
208    /// Resolve a Run reference on this state directory, including its owning repository.
209    pub async fn for_run(
210        state: Option<&Path>,
211        id: &RunId,
212        executable: &Path,
213    ) -> Result<Self, String> {
214        let state = crate::store::state_dir(state)?;
215        let repo = crate::store::read_run_repo(&state, id).await?;
216        Self::new(&repo, Some(&state), executable)
217    }
218
219    /// Bounded, best-effort operational diagnostics from the Run's worker.
220    pub fn worker_diagnostics(&self, id: &RunId) -> String {
221        crate::process::run_worker_diagnostics(&self.state, id)
222    }
223
224    /// Set the origin for new Runs started in this context, without changing read scope.
225    #[must_use]
226    pub fn with_origin(self, origin: Origin) -> Self {
227        Self { origin, ..self }
228    }
229
230    /// Public-library convenience; packaged callers normally pass their own executable to `new`.
231    pub fn discover(repo: &Path, state: Option<&Path>) -> Result<Self, String> {
232        let executable = process::artifactize_executable()?;
233        Self::new(repo, state, &executable)
234    }
235}
236
237/// Check whether a backend may take an Agent execution in this project and state.
238/// This checks admission, not credentials or provider access; a custom HTTP name
239/// needs a local registration, and an unsupported backend cannot take a slot.
240pub fn check_eval_backend(
241    backend: &crate::config::Backend,
242    state: Option<&Path>,
243    repo: Option<&Path>,
244) -> Result<(), crate::agent::error::Failure> {
245    backend.admit(|name| {
246        let providers = crate::auth::providers::list(state, repo)?;
247        Ok(providers.custom.contains_key(name.as_str()))
248    })
249}
250
251pub async fn start(
252    context: &Context,
253    selection: &Selection,
254    options: &VerifyOptions,
255    request_key: Option<RequestKey>,
256) -> Result<RunObservation, String> {
257    start_with_args_hash(context, selection, options, request_key, None).await
258}
259
260/// Start a Run with an optional attempt-argument fingerprint.
261pub(crate) async fn start_with_args_hash(
262    context: &Context,
263    selection: &Selection,
264    options: &VerifyOptions,
265    request_key: Option<RequestKey>,
266    request_args_hash: Option<String>,
267) -> Result<RunObservation, String> {
268    start_observing_launch_with_hash(
269        context,
270        selection,
271        options,
272        request_key,
273        request_args_hash,
274        |_, _| {},
275    )
276    .await
277}
278
279/// Transfer the supervisor's birth identity at launch, before saving or reading any receipt.
280#[doc(hidden)]
281pub async fn start_observing_launch(
282    context: &Context,
283    selection: &Selection,
284    options: &VerifyOptions,
285    request_key: Option<RequestKey>,
286    launched: impl FnOnce(&RunId, process::ChildIdentity),
287) -> Result<RunObservation, String> {
288    start_observing_launch_with_hash(context, selection, options, request_key, None, launched).await
289}
290
291async fn start_observing_launch_with_hash(
292    context: &Context,
293    selection: &Selection,
294    options: &VerifyOptions,
295    request_key: Option<RequestKey>,
296    request_args_hash: Option<String>,
297    launched: impl FnOnce(&RunId, process::ChildIdentity),
298) -> Result<RunObservation, String> {
299    // Keys are attempt identity, not checkout identity. Retry before discovering declarations.
300    if let Some(key) = &request_key
301        && crate::platform::paths::target_is_file(&context.state.join(store::DATABASE))
302    {
303        let receipts = Receipts::open(&context.state, &context.repo).await?;
304        let result = receipts
305            .keyed_run(&context.repo, key, request_args_hash.as_deref())
306            .await;
307        let closed = receipts.close().await;
308        if let Some(id) = result.and_then(|id| closed.map(|()| id))? {
309            return status(context, &id).await;
310        }
311    }
312    let (id, accepted) = crate::project::verify::reserve(
313        &context.repo,
314        Some(&context.state),
315        selection,
316        options,
317        request_key.as_ref(),
318        request_args_hash.as_deref(),
319        &context.origin,
320    )
321    .await?;
322    if accepted {
323        let receipts = Receipts::open(&context.state, &context.repo).await?;
324        let result = async {
325            let launch =
326                process::launch_run(&context.executable, &id, &context.repo, &context.state);
327            let admitted = match launch {
328                Ok(identity) => {
329                    launched(&id, identity);
330                    receipts.admit(&id, identity).await
331                }
332                Err(error) => Err(error.to_string()),
333            };
334            if let Err(error) = admitted {
335                worker::fail(&receipts, &id, FailureCode::SpawnFailed, error.clone()).await?;
336                return Err(format!("Run {id} handoff failed: {error}"));
337            }
338            Ok(())
339        }
340        .await;
341        let closed = receipts.close().await;
342        result.and(closed)?;
343    }
344    // Preparing the Run read the whole workspace and built its definitions, all freed by now;
345    // a caller that goes on to wait for the Run should not keep that memory while it waits.
346    crate::platform::release_free_memory();
347    status(context, &id).await
348}
349
350#[derive(Debug, Clone, Serialize)]
351pub struct CancelAcknowledgement {
352    pub run: RunId,
353    pub state: State,
354    pub cancellation_requested: bool,
355}
356pub async fn cancel(context: &Context, id: &RunId) -> Result<CancelAcknowledgement, String> {
357    // The compact observation checks the repository and settles a Run whose worker died.
358    let current = status(context, id).await?;
359    let receipts = Receipts::open(&context.state, &context.repo).await?;
360    let result = receipts.request_cancel(id).await;
361    let closed = receipts.close().await;
362    let (saved, control) = result.and_then(|saved| closed.map(|()| saved))?;
363    Ok(CancelAcknowledgement {
364        run: id.clone(),
365        state: observe::state_for(saved, control.as_ref(), &current.counts),
366        cancellation_requested: control.as_ref().is_some_and(Control::is_cancelling),
367    })
368}
369
370fn owner_died(status: crate::types::RunStatus, control: Option<&Control>) -> Result<bool, String> {
371    if !status.is_open() {
372        return Ok(false);
373    }
374    let owner = control.and_then(|control| match control.worker {
375        Worker::Starting { launcher } => Some(launcher),
376        Worker::Admitted { owner } => Some(owner),
377        Worker::Legacy => None,
378    });
379    Ok(owner.is_some() && !process::is_alive(owner).map_err(|error| error.to_string())?)
380}
381
382pub(crate) async fn reconcile(
383    state: &Path,
384    view: store::RunView,
385) -> Result<store::RunView, String> {
386    if owner_died(view.run.status(), view.run.control.as_ref())? {
387        worker::recover(state, &view).await?;
388        return store::read_run(state, &view.run.id).await;
389    }
390    Ok(view)
391}