quilt-cli 0.36.2

Local-first data versioning for AI agent workflows: commit immutable data packages on your own machine, then sync them with S3 to share.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
use quilt_rs::flow::UserMeta;
use quilt_rs::io::remote::HostConfig;
use quilt_rs::io::remote::WorkflowIntent;
use quilt_rs::lineage::CommitState;
use quilt_uri::Namespace;
use tracing::log;

use crate::cli::Error;
use crate::cli::model::Commands;
use crate::cli::output::Render;
use crate::cli::output::Std;

#[derive(Clone, Debug)]
pub struct Input {
    pub message: String,
    pub namespace: Namespace,
    pub user_meta: UserMeta,
    pub workflow: WorkflowIntent,
    pub host_config: Option<HostConfig>,
}

#[derive(Debug)]
pub struct Output {
    pub commit: CommitState,
}

impl std::fmt::Display for Output {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, r#"New commit "{}" created"#, self.commit.hash)
    }
}

impl Render for Output {
    fn to_json(&self) -> serde_json::Value {
        serde_json::json!({ "hash": &self.commit.hash })
    }
}

pub async fn command(m: impl Commands, args: Input) -> Std {
    Std::from_result(m.commit(args).await)
}

async fn commit_package(
    local_domain: &quilt_rs::LocalDomain,
    namespace: Namespace,
    message: String,
    user_meta: UserMeta,
    workflow: WorkflowIntent,
    host_config: Option<HostConfig>,
) -> Result<CommitState, Error> {
    match local_domain.get_installed_package(&namespace).await? {
        Some(installed_package) => {
            // Preserve the requested id before the intent is consumed so we can
            // warn if a caller-chosen workflow gets dropped for lack of a remote.
            let named_id = match &workflow {
                WorkflowIntent::Named(id) => Some(id.clone()),
                WorkflowIntent::BucketDefault | WorkflowIntent::NoWorkflow => None,
            };
            let workflow = installed_package.resolve_workflow(workflow).await?;
            // A remote-less package has no workflows config to resolve against,
            // so a `Named` intent silently resolves to nothing. Warn instead of
            // dropping it quietly — the workflow can be chosen at push/set-remote.
            if workflow.is_none()
                && let Some(id) = named_id
            {
                log::warn!(
                    "workflow '{id}' not applied: package has no remote yet; choose it at push/set-remote."
                );
            }
            Ok(installed_package
                .commit(message, user_meta, workflow, host_config)
                .await?)
        }
        None => Err(Error::NamespaceNotFound(namespace)),
    }
}

pub async fn model(
    local_domain: &quilt_rs::LocalDomain,
    Input {
        message,
        namespace,
        user_meta,
        workflow,
        host_config,
    }: Input,
) -> Result<Output, Error> {
    let commit = commit_package(
        local_domain,
        namespace,
        message,
        user_meta,
        workflow,
        host_config,
    )
    .await?;
    Ok(Output { commit })
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::path::PathBuf;

    use test_log::test;

    use crate::cli::create;
    use crate::cli::model::create_model_in_temp_dir;
    use crate::cli::model::install_package_into_temp_dir;
    use crate::cli::output::Render;

    use quilt_rs::io::storage::ByteStream;

    use quilt_rs::io::storage::LocalStorage;
    use quilt_rs::io::storage::Storage;

    /// Verify the commit of that package:
    ///  * workflow/config.yml exists
    ///  * workflow id is not set
    ///  * no files to commit,
    #[test(tokio::test)]
    async fn live_commit_package_with_message_and_null_workflow() -> Result<(), Error> {
        use crate::cli::fixtures::packages::workflow_null as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: UserMeta::Keep,
                    workflow: WorkflowIntent::NoWorkflow,
                    host_config: None,
                },
            )
            .await?;

            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    /// Bucket-default intent (`workflow: None, no_workflow: false`) against a
    /// bucket whose `workflows/config.yml` is present but declares no top-level
    /// `default_workflow` (the `udp-spec` bucket used by `workflow_null`).
    ///
    /// In that case `resolve_workflow` produces the same null-id workflow record
    /// as an explicit `NoWorkflow` opt-out, so the manifest bytes — and thus the
    /// top-hash — are byte-identical to the `NoWorkflow` case pinned by
    /// [`test_commit_package_with_message_and_null_workflow`]. This documents the
    /// equivalence rather than introducing a new anchor.
    #[test(tokio::test)]
    async fn live_commit_package_bucket_default_equals_null_workflow() -> Result<(), Error> {
        use crate::cli::fixtures::packages::workflow_null as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: UserMeta::Keep,
                    workflow: WorkflowIntent::BucketDefault,
                    host_config: None,
                },
            )
            .await?;

            // Same hash as the explicit `NoWorkflow` commit: the config has no
            // `default_workflow`, so bucket-default resolves to the null-id record.
            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    /// A commit that violates its workflow's `metadata_schema` must surface a
    /// clear CLI error. The `my-workflow` gate requires `Date`/`Name`/`Owner`/
    /// `Type` in the package metadata; committing with `Clear` (no metadata)
    /// against that same workflow is rejected, and the message the user sees
    /// must name the failing rule (`metadata_schema`) and every missing field.
    #[test(tokio::test)]
    async fn live_commit_rejected_by_workflow_surfaces_clear_error() -> Result<(), Error> {
        use crate::cli::fixtures::packages::my_workflow as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        let local_domain = m.get_local_domain();

        let err = model(
            local_domain,
            Input {
                message: pkg::MESSAGE.to_string(),
                namespace: pkg::NAMESPACE.into(),
                user_meta: UserMeta::Clear,
                workflow: WorkflowIntent::Named("my-workflow".to_string()),
                host_config: None,
            },
        )
        .await
        .unwrap_err();

        let message = err.to_string();
        // The CLI wraps the quilt-rs error transparently, so the validator's own
        // wording reaches the user verbatim.
        assert!(
            message.starts_with("quilt_rs error: package does not satisfy the workflow"),
            "message must announce a workflow rejection, got: {message}"
        );
        // Names the failing rule …
        assert!(
            message.contains("metadata_schema"),
            "message must name the failing rule, got: {message}"
        );
        // … and every field the schema requires (order-independent).
        for field in ["Date", "Name", "Owner", "Type"] {
            assert!(
                message.contains(field),
                "message must name the missing field {field}, got: {message}"
            );
        }

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_commit_package_with_workflow_and_meta() -> Result<(), Error> {
        use crate::cli::fixtures::packages::my_workflow as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: UserMeta::Set(serde_json::json!({
                        "Date": "2025-12-31",
                        "Name": "Foo",
                        "Owner": "Kevin",
                        "Type": "NGS"
                    })),
                    workflow: WorkflowIntent::Named("my-workflow".to_string()),
                    host_config: None,
                },
            )
            .await?;

            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    /// Verify the commit of that package:
    ///  * workflow/config.yml DOESN'T exists
    ///  * workflow id is not set
    ///  * no files to commit,
    #[test(tokio::test)]
    async fn live_commit_package_with_message_only() -> Result<(), Error> {
        use crate::cli::fixtures::packages::no_workflows_message_only as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: UserMeta::Keep,
                    workflow: WorkflowIntent::NoWorkflow,
                    host_config: None,
                },
            )
            .await?;

            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_throwing_error_when_workflow_set_but_no_workflows_config() -> Result<(), Error> {
        use crate::cli::fixtures::packages::no_workflows_message_only as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: UserMeta::Keep,
                    workflow: WorkflowIntent::Named("Anything".to_string()),
                    host_config: None,
                },
            )
            .await;

            assert_eq!(
                output.unwrap_err().to_string(),
                r#"quilt_rs error: Workflow error: There is no workflows config, but the workflow "Anything" is set"#
            );
        }

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_commit_package_with_meta_only() -> Result<(), Error> {
        use crate::cli::fixtures::packages::no_workflows_with_meta as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: "Initial".to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: UserMeta::Set(serde_json::json!({
                        // NOTE: will be sorted
                        "C": "D",
                        "c": "d",
                        "a": "b",
                        "A": "B",
                        "e": 123,
                        "f": null
                    })),
                    workflow: WorkflowIntent::NoWorkflow,
                    host_config: None,
                },
            )
            .await?;

            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    /// A `Named` intent on a remote-less (local-only) package has no workflows
    /// config to resolve against, so the workflow is dropped (and a warning is
    /// logged). The commit still succeeds and stamps no workflow — identical to
    /// the outcome of an explicit `NoWorkflow` opt-out on the same package.
    #[test(tokio::test)]
    async fn test_commit_named_workflow_without_remote_drops_workflow() -> Result<(), Error> {
        let (m, _temp_dir) = create_model_in_temp_dir().await?;
        let namespace: Namespace = ("local", "no_remote").into();

        let create_output = m
            .create(create::Input {
                namespace: namespace.clone(),
                source: None,
                message: None,
            })
            .await?;

        // A caller-chosen workflow that cannot be applied yet — no remote.
        let output = model(
            m.get_local_domain(),
            Input {
                message: "local commit".to_string(),
                namespace: namespace.clone(),
                user_meta: UserMeta::Keep,
                workflow: WorkflowIntent::Named("some-workflow".to_string()),
                host_config: None,
            },
        )
        .await?;

        assert!(!output.commit.hash.is_empty(), "commit should succeed");

        // No workflow was stamped: the manifest header carries no workflow.
        let manifest = create_output.installed_package.manifest().await?;
        assert!(
            manifest.header.workflow.is_none(),
            "remote-less Named intent must not stamp a workflow"
        );

        Ok(())
    }

    #[test(tokio::test)]
    async fn live_model() -> Result<(), Error> {
        let uri = "quilt+s3://udp-spec#package=spec/quilt-rs@11c5f6dbd1bf1d8675c18aaaa963b2f0dced2f892c7406fa36c9cd17d3d31b73";

        // TODO: commit is not-modified when we commit the same file (timestamp.txt)
        // TODO: commit is modified when we modify a file (README.md)
        // let readme_logical_key = PathBuf::from("READ ME.md");
        let timestamp_logical_key = PathBuf::from("timestamp.txt");

        let (m, installed_package, _temp_dir) = install_package_into_temp_dir(uri).await?;

        let first_input = Input {
            message: "Test message".to_string(),
            namespace: ("spec", "quilt-rs").into(),
            user_meta: UserMeta::Clear,
            workflow: WorkflowIntent::NoWorkflow,
            host_config: None,
        };
        let hash_for_initial_test_commit =
            "d6e62c3c43ddd30447d99eede1c7280c017b15cc716037b74af7bb5230fbb61a";

        {
            let local_domain = m.get_local_domain();

            let output = model(local_domain, first_input.clone())
                .await
                .expect("Failed to commit");

            assert_eq!(
                format!("{output}"),
                format!("New commit \"{}\" created", hash_for_initial_test_commit)
            );
        }

        {
            let local_domain = m.get_local_domain();
            let second_commit = model(local_domain, first_input)
                .await
                .expect("Failed to commit second commit which is identical to the first one");

            assert_eq!(second_commit.commit.hash, hash_for_initial_test_commit);
            assert_eq!(
                second_commit.commit.prev_hashes,
                vec![hash_for_initial_test_commit]
            );
        }

        {
            let local_domain = m.get_local_domain();
            let third_commit = model(
                local_domain,
                Input {
                    message: "New commit message".to_string(),
                    namespace: ("spec", "quilt-rs").into(),
                    user_meta: UserMeta::Set(serde_json::json!({"key": "value"})),
                    workflow: WorkflowIntent::NoWorkflow,
                    host_config: None,
                },
            )
            .await
            .expect("Failed to commit third commit different from the first one");

            assert_eq!(
                third_commit.commit.hash,
                "e2a86408670c7a33f78758d72166333e4a96b6aadbb3b03d25fd6e209dc6e0b3"
            );
            assert_eq!(
                third_commit.commit.prev_hashes,
                vec![hash_for_initial_test_commit, hash_for_initial_test_commit]
            );
        }

        {
            let local_domain = m.get_local_domain();
            let not_found = model(
                local_domain,
                Input {
                    message: "Anything".to_string(),
                    namespace: ("a", "b").into(),
                    user_meta: UserMeta::Keep,
                    workflow: WorkflowIntent::NoWorkflow,
                    host_config: None,
                },
            )
            .await;

            assert_eq!(not_found.unwrap_err().to_string(), "Package a/b not found");
        }

        let working_dir = installed_package.package_home().await?;
        let storage = LocalStorage::new();
        storage
            .write_byte_stream(
                working_dir.join(timestamp_logical_key),
                ByteStream::from_static(b"1697916638"),
            )
            .await
            .expect("Failed to write timestamp.txt to the installed package working directory");
        {
            let local_domain = m.get_local_domain();
            let commit_the_same_file = model(
                local_domain,
                Input {
                    message: "Test message".to_string(),
                    namespace: ("spec", "quilt-rs").into(),
                    user_meta: UserMeta::Clear,
                    workflow: WorkflowIntent::NoWorkflow,
                    host_config: None,
                },
            )
            .await
            .expect("Failed to commit the same file ensuring the commit hash will persist");
            assert_eq!(
                commit_the_same_file.commit.hash,
                hash_for_initial_test_commit
            );
        }

        Ok(())
    }

    /// `Keep` (the CLI default when `--user-meta` is absent) inherits the
    /// installed revision's package-level metadata, so the hash covers the
    /// fixture's meta (`{"A": "B", "c": "d", "e": 123}`).
    #[test(tokio::test)]
    async fn live_model_keep_inherits_fixture_meta() -> Result<(), Error> {
        let uri = "quilt+s3://udp-spec#package=spec/quilt-rs@11c5f6dbd1bf1d8675c18aaaa963b2f0dced2f892c7406fa36c9cd17d3d31b73";
        let (m, _installed_package, _temp_dir) = install_package_into_temp_dir(uri).await?;
        let local_domain = m.get_local_domain();
        let output = model(
            local_domain,
            Input {
                message: "Test message".to_string(),
                namespace: ("spec", "quilt-rs").into(),
                user_meta: UserMeta::Keep,
                workflow: WorkflowIntent::NoWorkflow,
                host_config: None,
            },
        )
        .await?;
        assert_eq!(
            output.commit.hash,
            "b9853f32d9b87b28a617a51acbdb3dffdb0974053a3415dedfef3950c6e239ef"
        );
        Ok(())
    }

    #[test]
    fn json_carries_the_hash_and_no_timestamp() {
        let output = Output {
            commit: CommitState {
                timestamp: std::time::SystemTime::UNIX_EPOCH.into(),
                hash: "abc123".to_string(),
                prev_hashes: vec!["older".to_string()],
            },
        };

        assert_eq!(output.to_json().to_string(), r#"{"hash":"abc123"}"#);
    }
}