quilt-cli 0.36.0

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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use std::collections::BTreeSet;

use tracing::log;

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

use quilt_rs::InstalledPackage;
use quilt_rs::flow::Kept;
use quilt_rs::flow::Revision;
use quilt_rs::io::remote::Remote;
use quilt_rs::io::storage::Storage;
use quilt_uri::Namespace;

#[derive(Debug)]
pub struct Input {
    pub namespace: Namespace,
}

/// One revision this copy holds, with what `remove-revisions` would make of
/// it.
pub struct Row {
    revision: Revision,
    /// Why it is kept, in [`Kept`]'s order; empty when it is removable.
    kept: Vec<Kept>,
    /// What removing it alone frees. `None` when it is kept, or when the
    /// measure could not be read.
    frees: Option<u64>,
}

pub struct Output {
    rows: Vec<Row>,
    /// Whether `kept` and `frees` were worked out. `false` when the registry
    /// listing failed: without it an unpublished revision can't be told
    /// apart, so the log leaves both out rather than guess.
    judged: bool,
}

impl Row {
    fn kept_words(&self) -> String {
        self.kept
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(" \u{b7} ")
    }

    fn frees_words(&self) -> String {
        self.frees
            .map(quilt_rs::flow::format_bytes)
            .unwrap_or_default()
    }
}

impl std::fmt::Display for Output {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.rows.is_empty() {
            return write!(f, "No revisions");
        }

        // Widths in chars, which is what `{:<w$}` pads by: `ยท` is one.
        let width = |words: &dyn Fn(&Row) -> String, heading: &str| {
            self.rows
                .iter()
                .map(|row| words(row).chars().count())
                .chain([heading.len()])
                .max()
                .unwrap_or_default()
        };
        let kept_width = width(&Row::kept_words, "kept");
        let frees_width = width(&Row::frees_words, "frees");

        write!(f, "revision  obtained (UTC)       ")?;
        if self.judged {
            write!(f, "{:<kept_width$}  {:<frees_width$}  ", "kept", "frees")?;
        }
        writeln!(f, "message")?;
        for row in &self.rows {
            let revision = &row.revision;
            let short_hash: String = revision.hash.chars().take(8).collect();
            let message = revision
                .message
                .as_deref()
                .unwrap_or("\u{2205}")
                .replace(['\n', '\r'], " ");
            write!(
                f,
                "{short_hash}  {}  ",
                revision.obtained.format("%Y-%m-%d %H:%M:%S"),
            )?;
            if self.judged {
                write!(
                    f,
                    "{:<kept_width$}  {:<frees_width$}  ",
                    row.kept_words(),
                    row.frees_words()
                )?;
            }
            writeln!(f, "{message}")?;
        }
        Ok(())
    }
}

impl Render for Output {
    fn to_json(&self) -> serde_json::Value {
        let revisions: Vec<_> = self
            .rows
            .iter()
            .map(|row| {
                let kept = self
                    .judged
                    .then(|| row.kept.iter().map(ToString::to_string).collect::<Vec<_>>());
                serde_json::json!({
                    "hash": &row.revision.hash,
                    "obtained": row.revision.obtained.to_rfc3339(),
                    "message": row.revision.message.as_deref(),
                    "kept": kept,
                    "frees": row.frees,
                })
            })
            .collect();
        serde_json::json!({ "revisions": revisions })
    }
}

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

pub async fn model(
    local_domain: &quilt_rs::LocalDomain,
    Input { namespace }: Input,
) -> Result<Output, Error> {
    let Some(package) = local_domain.get_installed_package(&namespace).await? else {
        return Err(Error::NamespaceNotFound(namespace));
    };
    read(&package).await
}

/// `package`'s revisions, newest first, each with why it is kept
/// ([`quilt_rs::flow::protection`]) and what removing it alone frees.
///
/// A registry listing that fails is not the log's failure: it warns on
/// stderr and leaves `kept` and `frees` out. A measure that fails leaves only
/// `frees` out.
pub async fn read<S: Storage + Clone + Sync, R: Remote>(
    package: &InstalledPackage<S, R>,
) -> Result<Output, Error> {
    let namespace = &package.namespace;
    let lineage = package.lineage().await?;
    let history = match package.revision_history(&lineage).await {
        Ok(history) => history,
        Err(err) => {
            log::warn!(
                "Could not read the registry of {namespace}, so the log leaves out what is kept and what removing frees: {err}"
            );
            let rows = package
                .revisions()
                .await?
                .into_iter()
                .map(|revision| Row {
                    revision,
                    kept: Vec::new(),
                    frees: None,
                })
                .collect();
            return Ok(Output {
                rows,
                judged: false,
            });
        }
    };
    let kept = quilt_rs::flow::protection(&lineage, &history);
    let usage = match package.revision_usage().await {
        Ok(usage) => Some(usage),
        Err(err) => {
            log::warn!("Could not measure what removing revisions of {namespace} frees: {err}");
            None
        }
    };
    let rows = history
        .into_iter()
        .map(|entry| {
            let reasons = kept.get(&entry.revision.hash).cloned().unwrap_or_default();
            let frees = usage
                .as_ref()
                .filter(|_| reasons.is_empty())
                .map(|usage| usage.frees(&BTreeSet::from([entry.revision.hash.clone()])));
            Row {
                revision: entry.revision,
                kept: reasons,
                frees,
            }
        })
        .collect();
    Ok(Output { rows, judged: true })
}

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

    use quilt_rs::flow::UserMeta;
    use quilt_rs::io::remote::WorkflowIntent;

    use test_log::test;

    use crate::cli::commit;
    use crate::cli::create;
    use crate::cli::fixtures::old_revisions;
    use crate::cli::model::Commands;
    use crate::cli::model::create_model_in_temp_dir;

    fn row(hash: &str, obtained: &str, message: &str, kept: &[Kept], frees: Option<u64>) -> Row {
        Row {
            revision: Revision {
                hash: hash.to_string(),
                obtained: obtained.parse().expect("a time"),
                message: Some(message.to_string()),
            },
            kept: kept.to_vec(),
            frees,
        }
    }

    fn rows() -> Vec<Row> {
        vec![
            row(
                "a1b2c3d4e5f6",
                "2026-10-01T09:12:00Z",
                "fix labels",
                &[Kept::Current, Kept::NotPushed],
                None,
            ),
            row(
                "e5f6a7b8c9d0",
                "2026-09-28T14:03:11Z",
                "v3",
                &[Kept::Latest, Kept::Base],
                None,
            ),
            row(
                "0c9d8e7f6a5b",
                "2026-09-20T10:40:52Z",
                "v2",
                &[],
                Some(210_400),
            ),
        ]
    }

    /// A kept row says why and frees nothing; a removable one says what
    /// removing it frees.
    #[test]
    fn test_display() {
        let output = Output {
            rows: rows(),
            judged: true,
        };

        assert_eq!(
            output.to_string(),
            "revision  obtained (UTC)       kept                  frees     message\n\
             a1b2c3d4  2026-10-01 09:12:00  current \u{b7} not pushed            fix labels\n\
             e5f6a7b8  2026-09-28 14:03:11  latest \u{b7} base                   v3\n\
             0c9d8e7f  2026-09-20 10:40:52                        210.4 kB  v2\n"
        );
    }

    /// Without the registry listing the log leaves both columns out.
    #[test]
    fn test_display_unjudged() {
        let output = Output {
            rows: rows()
                .into_iter()
                .map(|row| Row {
                    kept: Vec::new(),
                    frees: None,
                    ..row
                })
                .collect(),
            judged: false,
        };

        assert_eq!(
            output.to_string(),
            "revision  obtained (UTC)       message\n\
             a1b2c3d4  2026-10-01 09:12:00  fix labels\n\
             e5f6a7b8  2026-09-28 14:03:11  v3\n\
             0c9d8e7f  2026-09-20 10:40:52  v2\n"
        );
        assert_eq!(
            output.to_json()["revisions"][0]["kept"],
            serde_json::Value::Null
        );
        assert_eq!(
            output.to_json()["revisions"][0]["frees"],
            serde_json::Value::Null
        );
    }

    #[tokio::test]
    async fn test_model_lists_local_revisions() -> Result<(), Error> {
        let (cli_model, _domain_temp_dir) = create_model_in_temp_dir().await?;
        let namespace = Namespace::from(("demo", "sales"));

        cli_model
            .create(create::Input {
                namespace: namespace.clone(),
                source: None,
                message: Some("initial import".to_string()),
            })
            .await?;

        let package = cli_model
            .get_local_domain()
            .get_installed_package(&namespace)
            .await?
            .unwrap();
        std::fs::write(package.package_home().await?.join("data.txt"), "one")?;

        cli_model
            .commit(commit::Input {
                message: "add east region".to_string(),
                namespace: namespace.clone(),
                user_meta: UserMeta::Keep,
                workflow: WorkflowIntent::NoWorkflow,
                host_config: None,
            })
            .await?;

        let output = model(
            cli_model.get_local_domain(),
            Input {
                namespace: namespace.clone(),
            },
        )
        .await?;

        assert_eq!(output.rows.len(), 2);
        // No remote means no registry: every revision is unpublished, so kept.
        assert!(
            output
                .rows
                .iter()
                .all(|row| !row.kept.is_empty() && row.frees.is_none()),
            "{output}"
        );
        assert_eq!(
            output.rows[0].revision.message.as_deref(),
            Some("add east region")
        );
        assert_eq!(
            output.rows[1].revision.message.as_deref(),
            Some("initial import")
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_model_orders_by_acquisition_time_not_lineage() -> Result<(), Error> {
        let (cli_model, _domain_temp_dir) = create_model_in_temp_dir().await?;
        let namespace = Namespace::from(("demo", "sales"));

        cli_model
            .create(create::Input {
                namespace: namespace.clone(),
                source: None,
                message: Some("r1 initial import".to_string()),
            })
            .await?;

        let package = cli_model
            .get_local_domain()
            .get_installed_package(&namespace)
            .await?
            .unwrap();
        std::fs::write(package.package_home().await?.join("data.txt"), "one")?;

        cli_model
            .commit(commit::Input {
                message: "r2 add east".to_string(),
                namespace: namespace.clone(),
                user_meta: UserMeta::Keep,
                workflow: WorkflowIntent::NoWorkflow,
                host_config: None,
            })
            .await?;

        let oldest = model(
            cli_model.get_local_domain(),
            Input {
                namespace: namespace.clone(),
            },
        )
        .await?
        .rows
        .pop()
        .expect("two revisions")
        .revision;
        assert_eq!(oldest.message.as_deref(), Some("r1 initial import"));

        // `obtained` is this copy's acquisition time, so re-acquiring the oldest
        // revision moves it to the top. This is the documented meaning of the
        // column, not an ordering bug: nothing on disk records when a revision
        // was *made*.
        // Rewriting the same bytes bumps the mtime; the manifest is
        // content-addressed, so its name and contents still agree.
        let manifest = package.paths.installed_manifest(&namespace, &oldest.hash);
        let bytes = std::fs::read(&manifest)?;
        std::fs::write(&manifest, &bytes)?;

        let output = model(cli_model.get_local_domain(), Input { namespace }).await?;
        assert_eq!(
            output
                .rows
                .iter()
                .map(|row| row.revision.message.as_deref().unwrap_or_default())
                .collect::<Vec<_>>(),
            ["r1 initial import", "r2 add east"]
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_model_orders_four_successive_commits_newest_first() -> Result<(), Error> {
        let (cli_model, _domain_temp_dir) = create_model_in_temp_dir().await?;
        let namespace = Namespace::from(("demo", "sales"));

        cli_model
            .create(create::Input {
                namespace: namespace.clone(),
                source: None,
                message: Some("r1 initial import".to_string()),
            })
            .await?;

        let package = cli_model
            .get_local_domain()
            .get_installed_package(&namespace)
            .await?
            .unwrap();
        let home = package.package_home().await?;

        for message in ["r2 add east", "r3 add west", "r4 fix header"] {
            std::fs::write(home.join("data.txt"), message)?;
            cli_model
                .commit(commit::Input {
                    message: message.to_string(),
                    namespace: namespace.clone(),
                    user_meta: UserMeta::Keep,
                    workflow: WorkflowIntent::NoWorkflow,
                    host_config: None,
                })
                .await?;
        }

        let output = model(cli_model.get_local_domain(), Input { namespace }).await?;

        let expected = [
            "r4 fix header",
            "r3 add west",
            "r2 add east",
            "r1 initial import",
        ];
        assert_eq!(
            output
                .rows
                .iter()
                .map(|row| row.revision.message.as_deref().unwrap_or_default())
                .collect::<Vec<_>>(),
            expected
        );

        // And the same order in the rendered output a user actually sees,
        // past the heading row.
        assert_eq!(
            output
                .to_string()
                .lines()
                .skip(1)
                .map(|line| line
                    .rsplit_once("  ")
                    .expect("columns are two-space separated")
                    .1
                    .to_string())
                .collect::<Vec<_>>(),
            expected
        );
        Ok(())
    }

    fn revision(hash: &str, message: Option<&str>) -> Row {
        Row {
            revision: Revision {
                hash: hash.to_string(),
                obtained: std::time::SystemTime::UNIX_EPOCH.into(),
                message: message.map(str::to_string),
            },
            kept: Vec::new(),
            frees: None,
        }
    }

    #[test]
    fn json_empty_history() {
        let output = Output {
            rows: Vec::new(),
            judged: true,
        };

        assert_eq!(output.to_json().to_string(), r#"{"revisions":[]}"#);
    }

    /// The table shows eight characters and a zoneless local-looking time.
    /// Neither is usable as input, so JSON carries the full hash and RFC 3339.
    #[test]
    fn json_carries_full_hashes_and_rfc3339_times() {
        let output = Output {
            rows: vec![
                revision("0123456789abcdef", Some("first")),
                Row {
                    kept: vec![Kept::Current, Kept::NotPushed],
                    ..revision("fedcba9876543210", None)
                },
            ],
            judged: true,
        };

        assert_eq!(
            output.to_json().to_string(),
            r#"{"revisions":[{"hash":"0123456789abcdef","obtained":"1970-01-01T00:00:00+00:00","message":"first","kept":[],"frees":null},{"hash":"fedcba9876543210","obtained":"1970-01-01T00:00:00+00:00","message":null,"kept":["current","not pushed"],"frees":null}]}"#
        );
    }

    /// Over a registry: the current and the unpublished revisions say why
    /// they are kept, and each old one what removing it alone frees.
    #[test(tokio::test)]
    async fn kept_and_frees_over_a_registry() -> Result<(), Error> {
        let (package, _dirs) = old_revisions::package().await?;

        let output = read(&package).await?;

        let said: Vec<(&str, String, Option<u64>)> = output
            .rows
            .iter()
            .map(|row| (row.revision.hash.as_str(), row.kept_words(), row.frees))
            .collect();
        assert_eq!(
            said,
            [
                ("local-rev", "unpublished".to_string(), None),
                (
                    "current-rev",
                    "current \u{b7} latest \u{b7} base".to_string(),
                    None
                ),
                ("old-3", String::new(), Some(0)),
                ("old-2", String::new(), Some(1_500)),
                ("old-1", String::new(), Some(210_400)),
            ]
        );
        let json = output.to_json();
        assert_eq!(
            json["revisions"][1]["kept"],
            serde_json::json!(["current", "latest", "base"])
        );
        assert_eq!(json["revisions"][1]["frees"], serde_json::Value::Null);
        assert_eq!(json["revisions"][4]["kept"], serde_json::json!([]));
        assert_eq!(json["revisions"][4]["frees"], 210_400);
        assert!(output.to_string().contains("210.4 kB"), "{output}");
        Ok(())
    }

    /// A registry that can't be listed doesn't fail the log: it lists the
    /// revisions without the kept and frees columns.
    #[test(tokio::test)]
    async fn an_unreadable_registry_leaves_kept_and_frees_out() -> Result<(), Error> {
        let (package, _dirs) = old_revisions::package_with_a_broken_registry().await?;

        let output = read(&package).await?;

        assert!(!output.judged);
        assert_eq!(output.rows.len(), 5);
        assert!(
            output
                .to_string()
                .starts_with("revision  obtained (UTC)       message\n"),
            "{output}"
        );
        assert_eq!(
            output.to_json()["revisions"][0]["kept"],
            serde_json::Value::Null
        );
        assert_eq!(
            output.to_json()["revisions"][0]["frees"],
            serde_json::Value::Null
        );
        Ok(())
    }
}