artifactize-core 0.33.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
use crate::store::{self, OwnedReceipts};
use serde_json::{Value, json};
use std::path::Path;

fn run(id: &str, repo: &Path, state: &Path, definitions: Value) -> store::Run {
    serde_json::from_value(json!({
        "id":id,"repoPath":repo,"stateDir":state,"status":"RUNNING",
        "createdAt":"2026-01-01T00:00:00Z","completedAt":null,
        "selection":{"kind":"all"},"definitions":definitions,"validation":null,"evidence":{}
    }))
    .unwrap()
}

fn request(run: &str, artifact: &str, repo: &Path) -> store::Request {
    crate::test_request::request(
        &format!("{artifact}/check"),
        "QUEUED",
        json!({"id":format!("{run}-{artifact}"),"runId":run,"cwd":repo}),
    )
    .request
    .as_ref()
    .clone()
}

const DEFINED: &str = r#"{"artifacts":{"app":{"path":"app"}},"evals":[{"id":"app/check","target":"app","deps":[],"declaration":{"title":"Check"}}]}"#;

async fn fixture() -> (
    tempfile::TempDir,
    std::path::PathBuf,
    OwnedReceipts,
    store::Run,
) {
    let root = crate::test_os::tempdir();
    let repo = root.path().join("repo");
    let state = root.path().join("state");
    std::fs::create_dir(&repo).unwrap();
    let receipts = OwnedReceipts::open(&state, &repo).await.unwrap();
    let saved = run(
        "run-1",
        &repo,
        &state,
        serde_json::from_str(DEFINED).unwrap(),
    );
    receipts
        .create_run(
            &saved,
            &[
                request("run-1", "app", &repo),
                request("run-1", "web", &repo),
            ],
        )
        .await
        .unwrap();
    (root, state, receipts, saved)
}

#[tokio::test]
async fn a_saved_run_keeps_its_first_definitions_when_saved_again() {
    let (_root, state, receipts, mut saved) = fixture().await;
    let first = store::read_run(&state, "run-1").await.unwrap();
    // Saving the Run again saves its state; the definitions it was started with stay.
    saved.jobs = Some(7);
    saved.definitions =
        serde_json::from_value(json!({"artifacts":{"web":{"path":"web"}},"evals":[]})).unwrap();
    receipts.save_run(&saved).await.unwrap();
    let read = store::read_run(&state, "run-1").await.unwrap();
    assert_eq!(read.run.jobs, Some(7));
    assert_eq!(
        serde_json::to_value(read.run.definitions.graph().unwrap()).unwrap(),
        serde_json::to_value(first.run.definitions.graph().unwrap()).unwrap()
    );
    let artifacts = read
        .run
        .definitions
        .graph()
        .unwrap()
        .artifacts
        .value()
        .unwrap();
    assert!(artifacts.contains_key("app") && !artifacts.contains_key("web"));
}

#[tokio::test]
async fn an_existing_reader_sees_the_updated_run_and_request() {
    let (_root, state, receipts, mut saved) = fixture().await;
    let id = "run-1".parse().unwrap();
    let mut reader = store::reader::Reader::default();
    let snapshot = |reader: &mut store::reader::Reader| {
        reader
            .snapshot(&state, |db, cache, state| {
                cache.selected(db, state, &id, false)
            })
            .unwrap()
            .unwrap()
            .0
    };
    let before = snapshot(&mut reader);
    let mut app = request("run-1", "app", saved.repo_path.as_path());
    app.state = store::RequestState::failed(
        "stopped".into(),
        None,
        "2026-01-01T00:01:00Z".parse().unwrap(),
    );
    receipts.save_request(&app).await.unwrap();
    let updated = snapshot(&mut reader);
    assert_eq!(updated.requests[0].error(), Some("stopped"));
    assert_eq!(updated.requests[1].status(), before.requests[1].status());
    assert_eq!(before.requests[0].error(), None);
    saved.jobs = Some(7);
    receipts.save_run(&saved).await.unwrap();
    let settled = snapshot(&mut reader);
    assert_eq!(settled.run.jobs, Some(7));
    assert_eq!(settled.requests[0].error(), Some("stopped"));
    assert_eq!(settled.requests[1].status(), before.requests[1].status());
}

/// Definitions of `count` Artifacts, each with a tool, an eval and a part relation; the eval
/// of Artifact `changed` has another title. Saved Artifacts carry their tools, so their
/// records are larger than the hashes naming them.
fn catalog(count: usize, changed: Option<usize>) -> Value {
    let names: Vec<_> = (0..count).map(|n| format!("member-{n}")).collect();
    json!({
        "version": 5,
        "artifacts": names.iter().map(|name| (name.clone(), json!({
            "path": format!("members/{name}"),
            "tags": ["catalog", "member", name],
            "views": {"agentTools": {"inspect.read": {
                "builtin": "read",
                "args": [format!("members/{name}/notes.md")],
                "description": format!("Read the notes of {name}. ").repeat(8),
            }}},
        }))).collect::<serde_json::Map<_, _>>(),
        "evals": names.iter().enumerate().map(|(n, name)| json!({
            "id": format!("{name}/review"),
            "target": name,
            "deps": [],
            "declaration": {
                "title": if changed == Some(n) { "Changed" } else { "Review the member against the catalog rules" },
            },
        })).collect::<Vec<_>>(),
        "relations": names.iter().skip(1).map(|name| json!({
            "source": name, "target": "member-0", "kind": "part",
        })).collect::<Vec<_>>(),
        "environment": {"HOME": null},
    })
}

/// Bytes the state holds for the saved definitions of every Run.
fn definition_bytes(state: &Path) -> i64 {
    rusqlite::Connection::open_with_flags(
        state.join(store::DATABASE),
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
    )
    .unwrap()
    .query_row(
        "SELECT (SELECT coalesce(sum(length(CAST(data AS BLOB))),0) FROM run_definitions)
            + (SELECT coalesce(sum(length(CAST(data AS BLOB))),0) FROM definition_records)",
        [],
        |row| row.get(0),
    )
    .unwrap()
}

async fn saved(state: &Path, id: &str) -> Value {
    let view = store::read_run(state, id).await.unwrap();
    serde_json::to_value(view.run.definitions.graph().unwrap()).unwrap()
}

/// The graph `definitions` decode to, as a reader sees it.
fn decoded(definitions: Value) -> Value {
    let definitions: store::definitions::Definitions = serde_json::from_value(definitions).unwrap();
    serde_json::to_value(definitions.graph().unwrap()).unwrap()
}

#[tokio::test]
async fn runs_over_the_same_declarations_keep_their_definitions_once() {
    let (_root, state, receipts, first) = fixture().await;
    let repo = first.repo_path.clone();
    let definitions = catalog(200, None);
    let whole = serde_json::to_string(&definitions).unwrap().len() as i64;
    receipts
        .create_run(&run("run-2", &repo, &state, definitions.clone()), &[])
        .await
        .unwrap();
    let before = definition_bytes(&state);
    let mut again = run("run-3", &repo, &state, definitions.clone());
    again.selection = crate::project::selection::Selection::Artifact {
        artifact_id: "member-7".parse().unwrap(),
    };
    receipts.create_run(&again, &[]).await.unwrap();
    // The second Run adds its own head, not another copy of the catalog.
    let added = definition_bytes(&state) - before;
    assert!(added * 100 < whole, "{added} bytes added for {whole}");
    assert_eq!(saved(&state, "run-2").await, decoded(definitions.clone()));
    assert_eq!(saved(&state, "run-3").await, decoded(definitions));

    // A changed declaration adds its own records, not the unchanged ones again.
    let before = definition_bytes(&state);
    let changed = catalog(200, Some(42));
    receipts
        .create_run(&run("run-4", &repo, &state, changed.clone()), &[])
        .await
        .unwrap();
    let added = definition_bytes(&state) - before;
    assert!(added * 2 < whole, "{added} bytes added for {whole}");
    assert_eq!(saved(&state, "run-4").await, decoded(changed));
}

#[tokio::test]
async fn a_run_whose_saved_definition_record_is_gone_does_not_read() {
    let (_root, state, receipts, first) = fixture().await;
    receipts
        .create_run(
            &run("run-2", &first.repo_path, &state, catalog(3, None)),
            &[],
        )
        .await
        .unwrap();
    rusqlite::Connection::open(state.join(store::DATABASE))
        .unwrap()
        .execute(
            "DELETE FROM definition_records WHERE data LIKE '%member-1/review%'",
            [],
        )
        .unwrap();
    let error = store::read_run(&state, "run-2").await.unwrap_err();
    assert!(error.contains("missing saved definition record"), "{error}");
    assert!(store::read_run(&state, "run-1").await.is_ok());
}

#[tokio::test]
async fn schema_14_definitions_are_shared_on_upgrade() {
    let (_root, state, receipts, first) = fixture().await;
    let repo = first.repo_path.clone();
    for id in ["run-2", "run-3"] {
        receipts
            .create_run(&run(id, &repo, &state, catalog(50, None)), &[])
            .await
            .unwrap();
    }
    let expected = saved(&state, "run-2").await;
    let wholes = [
        serde_json::to_string(&saved(&state, "run-2").await).unwrap(),
        serde_json::to_string(&saved(&state, "run-3").await).unwrap(),
    ];
    drop(receipts);
    // Back to schema 14: every Run's definitions whole in its row, one of them unreadable.
    let db = rusqlite::Connection::open(state.join(store::DATABASE)).unwrap();
    for (id, whole) in ["run-2", "run-3"].into_iter().zip(&wholes) {
        db.execute(
            "UPDATE run_definitions SET data=?,body=NULL WHERE run_id=?",
            [whole.as_str(), id],
        )
        .unwrap();
    }
    db.execute_batch(
        "UPDATE run_definitions SET data='{',body=NULL WHERE run_id='run-1';
        DROP INDEX request_listed; ALTER TABLE requests DROP COLUMN listed;
        ALTER TABLE run_definitions DROP COLUMN body; DROP TABLE definition_records;
        PRAGMA user_version=14;",
    )
    .unwrap();
    let before: i64 = db
        .query_row(
            "SELECT sum(length(CAST(data AS BLOB))) FROM run_definitions",
            [],
            |row| row.get(0),
        )
        .unwrap();
    drop(db);

    let receipts = OwnedReceipts::open(&state, &repo).await.unwrap();
    assert_eq!(saved(&state, "run-2").await, expected);
    assert_eq!(saved(&state, "run-3").await, expected);
    assert!(store::read_run(&state, "run-1").await.is_err());
    // Two Runs of one catalog now hold it once.
    let after = definition_bytes(&state);
    assert!(
        after * 3 < before * 2,
        "{after} bytes after, {before} before"
    );
    drop(receipts);
}

/// `catalog(count, None)` with `files` definition files of about `size` bytes each, the file
/// `changed` with other text.
fn with_sources(count: usize, files: usize, size: usize, changed: Option<usize>) -> Value {
    let mut definitions = catalog(count, None);
    definitions["sources"] = (0..files)
        .map(|n| {
            let line = format!("artf member-{n} = {{ path = \"members/member-{n}\" }}\n");
            let text = if changed == Some(n) {
                "// changed\n"
            } else {
                ""
            }
            .to_owned()
                + &line.repeat(size / line.len());
            json!({"path": format!(".artifactize/file-{n}.artf"), "text": text})
        })
        .collect();
    definitions
}

#[tokio::test]
async fn a_run_keeps_the_code_it_read_apart_from_its_definitions() {
    let (_root, state, receipts, first) = fixture().await;
    let repo = first.repo_path.clone();
    let definitions = with_sources(20, 40, 4_000, None);
    receipts
        .create_run(&run("run-2", &repo, &state, definitions.clone()), &[])
        .await
        .unwrap();
    // Reading the Run leaves its code out; its code's reader gets every file in order.
    let read = store::read_run(&state, "run-2").await.unwrap();
    assert!(read.run.definitions.graph().unwrap().sources.is_none());
    let sources = store::read_run_sources(&state, "run-2")
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        serde_json::to_value(&sources).unwrap(),
        definitions["sources"]
    );
    // A Run whose one file changed adds that file, not the code again.
    let before = definition_bytes(&state);
    receipts
        .create_run(
            &run("run-3", &repo, &state, with_sources(20, 40, 4_000, Some(7))),
            &[],
        )
        .await
        .unwrap();
    let added = definition_bytes(&state) - before;
    // Its file and the new body naming the files, a small part of the 160 kB of code.
    assert!(added * 10 < 40 * 4_000, "{added} bytes added");
    let sources = store::read_run_sources(&state, "run-3")
        .await
        .unwrap()
        .unwrap();
    assert!(sources[7].text.starts_with("// changed\n"));
    // A Run saved before Runs kept their code has none.
    assert_eq!(
        store::read_run_sources(&state, "run-1").await.unwrap(),
        None
    );
    drop(receipts);
}