artifactize-core 0.31.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Artifactize-owned verification: durable submission, observation and explicit cancellation.
mod follow;
#[cfg(test)]
#[path = "tests/lifetime.rs"]
mod lifetime_tests;
mod observe;
mod reference;
mod result;
mod summary;
mod watch;
mod worker;
pub use crate::store::{RunSummary, RunView};
use crate::{
    process,
    project::{VerifyOptions, selection::Selection},
    store::{self, Receipts},
    types::{FailureCode, RequestKey, RunId},
};
pub use follow::{Follow, FollowUpdate, RunFinished, reconcile_open, workspaces};
pub use observe::{
    Counts, RunObservation, State, reconcile_interrupted, status, view, wait, wait_for_change,
    wait_observing,
};
pub use reference::{Reference, reference};
pub use result::{
    Completion, Finding, PAGE_SIZE as RESULT_PAGE_SIZE, ResultCursor, ResultState, RunResultPage,
    RunVerdict, Signoff, completion, result,
};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
pub use summary::{
    Action, ActionRequest, ActionStatus, ActionWaitBound, INLINE_WAIT_SECONDS, RunActionSummary,
    SignoffStatus, WaitingSignoff, summary, wait_for_action,
};
pub use watch::{RunEvent, watch};
#[doc(hidden)]
pub use worker::{execute, supervise, supervise_observing_launch};

/// Page saved Runs from one workspace, or all workspaces in this state.
pub async fn list(
    state: &Path,
    repo: Option<&Path>,
    limit: u32,
    offset: u32,
) -> Result<Vec<RunSummary>, String> {
    store::read_runs(state, repo, limit, offset).await
}

/// Per-Run execution modes. Future modes extend this type, not transport signatures.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct RunModes {
    /// Start work before its dependency gates resolve, and cancel it once one fails.
    pub speculate: bool,
    /// Never wait on or be blocked by dependency gates; a Human eval still waits for the
    /// machine evals of its own Artifact.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub ignore_gates: bool,
}
impl RunModes {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }

    /// How the graph treats gates in a Run with these modes.
    pub(crate) fn gating(&self) -> crate::graph::Gating {
        crate::graph::Gating {
            errors_block: self.speculate,
            ignore_dependencies: self.ignore_gates,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Activity {
    Preparing,
    Executing,
    Publishing,
    Waiting,
    Cancelling,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum Worker {
    Starting {
        launcher: process::ChildIdentity,
    },
    Admitted {
        owner: process::ChildIdentity,
    },
    /// Old records have no worker identity and are not evidence of owner death.
    Legacy,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(from = "ControlWire", into = "ControlWire")]
pub struct Control {
    pub worker: Worker,
    /// The supervisor keeps worker files open until its executor has exited and been checked.
    pub supervisor: Option<process::ChildIdentity>,
    pub activity: Activity,
    /// The scheduler has reached its sign-off idle grace, not a machine admission wait.
    pub(crate) only_signoffs: bool,
    pub failure_code: Option<FailureCode>,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ControlWire {
    worker: Worker,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    supervisor: Option<process::ChildIdentity>,
    activity: Activity,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    only_signoffs: bool,
    #[serde(default)]
    cancellation_requested: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    failure_code: Option<FailureCode>,
}

impl From<ControlWire> for Control {
    fn from(wire: ControlWire) -> Self {
        Self {
            worker: wire.worker,
            supervisor: wire.supervisor,
            activity: if wire.cancellation_requested {
                Activity::Cancelling
            } else {
                wire.activity
            },
            failure_code: wire.failure_code,
            only_signoffs: wire.only_signoffs,
        }
    }
}

impl From<Control> for ControlWire {
    fn from(control: Control) -> Self {
        Self {
            worker: control.worker,
            supervisor: control.supervisor,
            activity: control.activity,
            only_signoffs: control.only_signoffs,
            cancellation_requested: control.is_cancelling(),
            failure_code: control.failure_code,
        }
    }
}

impl Control {
    pub fn is_cancelling(&self) -> bool {
        self.activity == Activity::Cancelling
    }

    pub(crate) fn starting() -> Result<Self, String> {
        Ok(Self {
            worker: Worker::Starting {
                launcher: process::child_identity(std::process::id()).map_err(|e| e.to_string())?,
            },
            supervisor: None,
            activity: Activity::Preparing,
            failure_code: None,
            only_signoffs: false,
        })
    }
    pub(crate) fn legacy() -> Self {
        Self {
            worker: Worker::Legacy,
            supervisor: None,
            activity: Activity::Executing,
            failure_code: None,
            only_signoffs: false,
        }
    }
}

/// The surface that accepted a new Run. Old receipts have no known origin.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum Origin {
    Cli,
    Mcp,
    #[serde(other)]
    Unknown,
}

/// Bound repository/state and trusted executable, resolved once by the interface at startup.
#[derive(Debug, Clone)]
pub struct Context {
    pub(crate) repo: PathBuf,
    pub(crate) state: PathBuf,
    executable: PathBuf,
    origin: Origin,
}
impl Context {
    /// The canonical repository this endpoint serves.
    pub fn repo(&self) -> &Path {
        &self.repo
    }

    /// The canonical state directory shared by this endpoint and its Run workers.
    pub fn state(&self) -> &Path {
        &self.state
    }

    pub fn new(repo: &Path, state: Option<&Path>, executable: &Path) -> Result<Self, String> {
        Ok(Self {
            repo: crate::workspace::canonical_target(repo).map_err(|e| e.to_string())?,
            state: crate::workspace::canonical_target(&store::state_dir(state)?)
                .map_err(|e| e.to_string())?,
            executable: executable.to_path_buf(),
            origin: Origin::Cli,
        })
    }
    /// Resolve a Run reference on this state directory, including its owning repository.
    pub async fn for_run(
        state: Option<&Path>,
        id: &RunId,
        executable: &Path,
    ) -> Result<Self, String> {
        let state = crate::store::state_dir(state)?;
        let repo = crate::store::read_run_repo(&state, id).await?;
        Self::new(&repo, Some(&state), executable)
    }

    /// Bounded, best-effort operational diagnostics from the Run's worker.
    pub fn worker_diagnostics(&self, id: &RunId) -> String {
        crate::process::run_worker_diagnostics(&self.state, id)
    }

    /// Set the origin for new Runs started in this context, without changing read scope.
    #[must_use]
    pub fn with_origin(self, origin: Origin) -> Self {
        Self { origin, ..self }
    }

    /// Public-library convenience; packaged callers normally pass their own executable to `new`.
    pub fn discover(repo: &Path, state: Option<&Path>) -> Result<Self, String> {
        let executable = process::artifactize_executable()?;
        Self::new(repo, state, &executable)
    }
}

/// Check whether a backend may take an Agent execution in this project and state.
/// This checks admission, not credentials or provider access; a custom HTTP name
/// needs a local registration, and an unsupported backend cannot take a slot.
pub fn check_eval_backend(
    backend: &crate::config::Backend,
    state: Option<&Path>,
    repo: Option<&Path>,
) -> Result<(), crate::agent::error::Failure> {
    backend.admit(|name| {
        let providers = crate::auth::providers::list(state, repo)?;
        Ok(providers.custom.contains_key(name.as_str()))
    })
}

pub async fn start(
    context: &Context,
    selection: &Selection,
    options: &VerifyOptions,
    request_key: Option<RequestKey>,
) -> Result<RunObservation, String> {
    start_with_args_hash(context, selection, options, request_key, None).await
}

/// Start a Run with an optional attempt-argument fingerprint.
pub(crate) async fn start_with_args_hash(
    context: &Context,
    selection: &Selection,
    options: &VerifyOptions,
    request_key: Option<RequestKey>,
    request_args_hash: Option<String>,
) -> Result<RunObservation, String> {
    start_observing_launch_with_hash(
        context,
        selection,
        options,
        request_key,
        request_args_hash,
        |_, _| {},
    )
    .await
}

/// Transfer the supervisor's birth identity at launch, before saving or reading any receipt.
#[doc(hidden)]
pub async fn start_observing_launch(
    context: &Context,
    selection: &Selection,
    options: &VerifyOptions,
    request_key: Option<RequestKey>,
    launched: impl FnOnce(&RunId, process::ChildIdentity),
) -> Result<RunObservation, String> {
    start_observing_launch_with_hash(context, selection, options, request_key, None, launched).await
}

async fn start_observing_launch_with_hash(
    context: &Context,
    selection: &Selection,
    options: &VerifyOptions,
    request_key: Option<RequestKey>,
    request_args_hash: Option<String>,
    launched: impl FnOnce(&RunId, process::ChildIdentity),
) -> Result<RunObservation, String> {
    // Keys are attempt identity, not checkout identity. Retry before discovering declarations.
    if let Some(key) = &request_key
        && crate::platform::paths::target_is_file(&context.state.join(store::DATABASE))
    {
        let receipts = Receipts::open(&context.state, &context.repo).await?;
        let result = receipts
            .keyed_run(&context.repo, key, request_args_hash.as_deref())
            .await;
        let closed = receipts.close().await;
        if let Some(id) = result.and_then(|id| closed.map(|()| id))? {
            return status(context, &id).await;
        }
    }
    let (id, accepted) = crate::project::verify::reserve(
        &context.repo,
        Some(&context.state),
        selection,
        options,
        request_key.as_ref(),
        request_args_hash.as_deref(),
        &context.origin,
    )
    .await?;
    if accepted {
        let receipts = Receipts::open(&context.state, &context.repo).await?;
        let result = async {
            let launch =
                process::launch_run(&context.executable, &id, &context.repo, &context.state);
            let admitted = match launch {
                Ok(identity) => {
                    launched(&id, identity);
                    receipts.admit(&id, identity).await
                }
                Err(error) => Err(error.to_string()),
            };
            if let Err(error) = admitted {
                worker::fail(&receipts, &id, FailureCode::SpawnFailed, error.clone()).await?;
                return Err(format!("Run {id} handoff failed: {error}"));
            }
            Ok(())
        }
        .await;
        let closed = receipts.close().await;
        result.and(closed)?;
    }
    // Preparing the Run read the whole workspace and built its definitions, all freed by now;
    // a caller that goes on to wait for the Run should not keep that memory while it waits.
    crate::platform::release_free_memory();
    status(context, &id).await
}

#[derive(Debug, Clone, Serialize)]
pub struct CancelAcknowledgement {
    pub run: RunId,
    pub state: State,
    pub cancellation_requested: bool,
}
pub async fn cancel(context: &Context, id: &RunId) -> Result<CancelAcknowledgement, String> {
    // The compact observation checks the repository and settles a Run whose worker died.
    let current = status(context, id).await?;
    let receipts = Receipts::open(&context.state, &context.repo).await?;
    let result = receipts.request_cancel(id).await;
    let closed = receipts.close().await;
    let (saved, control) = result.and_then(|saved| closed.map(|()| saved))?;
    Ok(CancelAcknowledgement {
        run: id.clone(),
        state: observe::state_for(saved, control.as_ref(), &current.counts),
        cancellation_requested: control.as_ref().is_some_and(Control::is_cancelling),
    })
}

fn owner_died(status: crate::types::RunStatus, control: Option<&Control>) -> Result<bool, String> {
    if !status.is_open() {
        return Ok(false);
    }
    let owner = control.and_then(|control| match control.worker {
        Worker::Starting { launcher } => Some(launcher),
        Worker::Admitted { owner } => Some(owner),
        Worker::Legacy => None,
    });
    Ok(owner.is_some() && !process::is_alive(owner).map_err(|error| error.to_string())?)
}

pub(crate) async fn reconcile(
    state: &Path,
    view: store::RunView,
) -> Result<store::RunView, String> {
    if owner_died(view.run.status(), view.run.control.as_ref())? {
        worker::recover(state, &view).await?;
        return store::read_run(state, &view.run.id).await;
    }
    Ok(view)
}