void-cli 0.0.4

CLI for void — anonymous encrypted source control
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Stash command - save and restore working tree changes.
//!
//! Provides a stack-based mechanism for saving working tree changes and
//! restoring them later. Stashed changes are stored as encrypted commits.

use camino::Utf8PathBuf;
use serde::Serialize;
use std::path::Path;
use void_core::cid::ToVoidCid;
use void_core::crypto::SecretKey;
use void_core::metadata::ShardMap;
use void_core::pipeline::{commit_workspace, CommitOptions, SealOptions};
use void_core::workspace::checkout::{checkout_tree, CheckoutOptions};
use void_core::workspace::stage::{stage_paths, StageOptions};
use void_core::{cid, refs, stash, store};

use void_core::VoidContext;

use crate::context::{
    find_void_dir, load_signing_key, open_repo, signing_key_exists,
    void_err_to_cli,
};
use crate::output::{run_command, CliError, CliOptions};

/// Stash subcommand action.
#[derive(Debug, Clone)]
pub enum StashAction {
    /// Save current changes to stash (default action).
    Save { message: Option<String> },
    /// List all stash entries.
    List,
    /// Apply and remove a stash entry.
    Pop { index: Option<u32> },
    /// Remove a stash entry without applying.
    Drop { index: Option<u32> },
    /// Remove all stash entries.
    Clear,
}

/// Command-line arguments for stash.
#[derive(Debug)]
pub struct StashArgs {
    pub action: StashAction,
}

/// JSON output for stash list action.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StashEntryOutput {
    pub index: u32,
    pub commit_cid: String,
    pub original_head: String,
    pub message: Option<String>,
    pub timestamp: u64,
}

/// JSON output for stash command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StashOutput {
    /// The action performed: "list", "save", "pop", "drop", or "clear".
    pub action: String,
    /// Stash entries (for list action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entries: Option<Vec<StashEntryOutput>>,
    /// Stash index (for save/pop/drop actions).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<u32>,
    /// Commit CID (for save action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit_cid: Option<String>,
    /// Original HEAD when stash was created (for pop action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub original_head: Option<String>,
    /// Stash message (for save/pop/drop actions).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// Number of entries cleared (for clear action).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<usize>,
}

/// Format a relative time string from a Unix timestamp.
fn format_relative_time(timestamp: u64) -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    let diff = now.saturating_sub(timestamp);

    if diff < 60 {
        "just now".to_string()
    } else if diff < 3600 {
        let mins = diff / 60;
        format!("{} minute{} ago", mins, if mins == 1 { "" } else { "s" })
    } else if diff < 86400 {
        let hours = diff / 3600;
        format!("{} hour{} ago", hours, if hours == 1 { "" } else { "s" })
    } else if diff < 604800 {
        let days = diff / 86400;
        format!("{} day{} ago", days, if days == 1 { "" } else { "s" })
    } else {
        let weeks = diff / 604800;
        format!("{} week{} ago", weeks, if weeks == 1 { "" } else { "s" })
    }
}

/// Run the stash command.
///
/// # Arguments
///
/// * `cwd` - Current working directory
/// * `args` - Stash arguments
/// * `opts` - CLI options
pub fn run(cwd: &Path, args: StashArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("stash", opts, |ctx| {
        let void_dir = find_void_dir(cwd)?;
        let repo = open_repo(cwd)?;
        let void_ctx = repo.context().clone();
        let vault = repo.vault().clone();
        let key = vault.stash_key().map_err(|e| void_err_to_cli(e.into()))?;

        match args.action {
            StashAction::List => run_list(ctx, &void_dir, key),
            StashAction::Save { message } => run_save(ctx, cwd, &void_dir, &vault, key, message, &void_ctx),
            StashAction::Pop { index } => run_pop(ctx, cwd, &void_dir, &vault, key, index.unwrap_or(0)),
            StashAction::Drop { index } => run_drop(ctx, &void_dir, key, index.unwrap_or(0)),
            StashAction::Clear => run_clear(ctx, &void_dir, key),
        }
    })
}

/// List all stash entries.
fn run_list(
    ctx: &mut crate::output::CommandContext,
    void_dir: &Path,
    key: &SecretKey,
) -> Result<StashOutput, CliError> {
    ctx.progress("Listing stash entries...");

    let stack = stash::read_stash_stack(void_dir, key).map_err(void_err_to_cli)?;

    let entries: Vec<StashEntryOutput> = stack
        .entries
        .iter()
        .map(|e| {
            let cid_str = cid::from_bytes(e.commit_cid.as_bytes())
                .map(|c| c.to_string())
                .unwrap_or_else(|_| hex::encode(e.commit_cid.as_bytes()));

            let original_head_str = cid::from_bytes(e.original_head.as_bytes())
                .map(|c| c.to_string())
                .unwrap_or_else(|_| hex::encode(e.original_head.as_bytes()));

            StashEntryOutput {
                index: e.index,
                commit_cid: cid_str,
                original_head: original_head_str,
                message: e.message.clone(),
                timestamp: e.timestamp,
            }
        })
        .collect();

    // Human-readable output
    if !ctx.use_json() {
        if entries.is_empty() {
            ctx.info("No stash entries.");
        } else {
            for entry in &entries {
                let msg = entry.message.as_deref().unwrap_or("WIP on HEAD");
                let time = format_relative_time(entry.timestamp);
                ctx.info(format!("stash@{{{}}}: {} ({})", entry.index, msg, time));
            }
        }
    }

    Ok(StashOutput {
        action: "list".to_string(),
        entries: Some(entries),
        index: None,
        commit_cid: None,
        original_head: None,
        message: None,
        count: None,
    })
}

/// Save current working tree changes to stash.
fn run_save(
    ctx: &mut crate::output::CommandContext,
    _cwd: &Path,
    void_dir: &Path,
    vault: &std::sync::Arc<void_core::crypto::KeyVault>,
    key: &SecretKey,
    message: Option<String>,
    void_ctx: &VoidContext,
) -> Result<StashOutput, CliError> {
    ctx.progress("Saving working directory to stash...");

    let void_dir_utf8 = Utf8PathBuf::try_from(void_dir.to_path_buf())
        .map_err(|e| CliError::internal(format!("invalid void_dir path: {}", e)))?;

    // Get current HEAD reference (need to know if symbolic or detached for later reset)
    let head_ref = refs::read_head(&void_dir_utf8)
        .map_err(void_err_to_cli)?
        .ok_or_else(|| CliError::not_found("HEAD is not set - nothing to stash"))?;

    // Also resolve HEAD to get the CID
    let head_cid = refs::resolve_head(&void_dir_utf8)
        .map_err(void_err_to_cli)?
        .ok_or_else(|| CliError::not_found("HEAD is not set - nothing to stash"))?;

    // Load config for repo_secret
    let config =
        void_core::config::load(void_dir).map_err(|e| CliError::internal(e.to_string()))?;
    let repo_secret = match config.repo_secret {
        Some(secret_hex) => {
            let bytes = hex::decode(&secret_hex)
                .map_err(|e| CliError::internal(format!("invalid repo_secret in config: {}", e)))?;
            if bytes.len() != 32 {
                return Err(CliError::internal(format!(
                    "repo_secret must be 32 bytes, got {}",
                    bytes.len()
                )));
            }
            let mut arr = [0u8; 32];
            arr.copy_from_slice(&bytes);
            void_core::crypto::RepoSecret::new(arr)
        }
        None => {
            return Err(CliError::internal(
                "Missing repoSecret in config. Repository may be corrupted.",
            ));
        }
    };

    // Stage all changes (including unstaged modifications and deletions) before creating stash commit
    // This mimics git stash behavior which captures the full working tree state
    ctx.progress("Staging all changes...");
    let stage_opts = StageOptions {
        ctx: void_ctx.clone(),
        patterns: vec![".".to_string()],
        observer: None,
    };
    let _stage_result = stage_paths(stage_opts).map_err(void_err_to_cli)?;

    // Note: We don't check if stage_result is empty because there might already be
    // staged changes from before. commit_workspace will fail if there's truly nothing to commit.

    // Create a commit from the current working tree
    let stash_message = message.clone().unwrap_or_else(|| "WIP on HEAD".to_string());

    // Load signing key if available (auto-sign like regular commits)
    let signing_key = if signing_key_exists() {
        load_signing_key().ok()
    } else {
        None
    };

    // Set up VoidContext with signing key and repo secret for SealOptions
    let mut stash_ctx = void_ctx.clone();
    stash_ctx.repo.secret = repo_secret;
    stash_ctx.crypto.signing_key = signing_key.map(std::sync::Arc::new);

    let seal_opts = SealOptions {
        ctx: stash_ctx,
        shard_map: ShardMap::new(64),
        content_key: None,
        parent_content_key: None,
    };

    let commit_opts = CommitOptions {
        seal: seal_opts,
        message: format!("stash: {}", stash_message),
        parent_cid: Some(head_cid.clone()),
        allow_data_loss: true, // Stash should capture current state
        foreign_parent: false,
    };

    ctx.progress("Creating stash commit...");

    let result = commit_workspace(commit_opts).map_err(void_err_to_cli)?;

    // Add to stash stack
    let mut stack = stash::read_stash_stack(void_dir, key).map_err(void_err_to_cli)?;
    stack.push(result.commit_cid.clone(), head_cid.clone(), message.clone());
    stash::write_stash_stack(void_dir, key, &stack).map_err(void_err_to_cli)?;

    // Restore the original HEAD (checkout the parent commit to reset working tree)
    ctx.progress("Restoring clean working directory...");

    let objects_dir = Utf8PathBuf::try_from(void_dir.join("objects"))
        .map_err(|e| CliError::internal(format!("invalid objects path: {}", e)))?;
    let store = store::FsStore::new(objects_dir).map_err(void_err_to_cli)?;

    let head_cid_obj = cid::from_bytes(head_cid.as_bytes())
        .map_err(|e| CliError::internal(format!("invalid HEAD CID: {}", e)))?;

    let workspace = void_dir
        .parent()
        .ok_or_else(|| CliError::internal("void_dir has no parent"))?;

    let checkout_opts = CheckoutOptions {
        paths: None,
        force: true,
        observer: None,
        workspace_dir: None,
        include_large: false,
    };

    checkout_tree(&store, &**vault, &head_cid_obj, workspace, &checkout_opts)
        .map_err(void_err_to_cli)?;

    // Reset HEAD back to original (commit_workspace updated it to stash commit)
    match head_ref {
        refs::HeadRef::Symbolic(branch) => {
            refs::write_branch(&void_dir_utf8, &branch, &head_cid)
                .map_err(void_err_to_cli)?;
        }
        refs::HeadRef::Detached(_) => {
            refs::write_head(
                &void_dir_utf8,
                &refs::HeadRef::Detached(head_cid.clone()),
            )
            .map_err(void_err_to_cli)?;
        }
    }

    // Human-readable output
    if !ctx.use_json() {
        let msg = message.as_deref().unwrap_or("WIP on HEAD");
        ctx.info(format!("Saved working directory to stash@{{0}}: {}", msg));
    }

    Ok(StashOutput {
        action: "save".to_string(),
        entries: None,
        index: Some(0),
        commit_cid: Some(result.commit_cid.to_cid_string()),
        original_head: None,
        message,
        count: None,
    })
}

/// Apply and remove a stash entry.
fn run_pop(
    ctx: &mut crate::output::CommandContext,
    _cwd: &Path,
    void_dir: &Path,
    vault: &std::sync::Arc<void_core::crypto::KeyVault>,
    key: &SecretKey,
    index: u32,
) -> Result<StashOutput, CliError> {
    ctx.progress(format!("Applying stash@{{{}}}...", index));

    let mut stack = stash::read_stash_stack(void_dir, key).map_err(void_err_to_cli)?;

    let entry = stack
        .get(index)
        .cloned()
        .ok_or_else(|| CliError::not_found(format!("stash@{{{}}} not found", index)))?;

    // Apply the stash (checkout the stash commit)
    let objects_dir = Utf8PathBuf::try_from(void_dir.join("objects"))
        .map_err(|e| CliError::internal(format!("invalid objects path: {}", e)))?;
    let store = store::FsStore::new(objects_dir).map_err(void_err_to_cli)?;

    let stash_cid = cid::from_bytes(entry.commit_cid.as_bytes())
        .map_err(|e| CliError::internal(format!("invalid stash commit CID: {}", e)))?;

    let workspace = void_dir
        .parent()
        .ok_or_else(|| CliError::internal("void_dir has no parent"))?;

    let checkout_opts = CheckoutOptions {
        paths: None,
        force: true,
        observer: None,
        workspace_dir: None,
        include_large: false,
    };

    checkout_tree(&store, &**vault, &stash_cid, workspace, &checkout_opts).map_err(void_err_to_cli)?;

    // Remove from stash stack
    stack.remove(index);
    stash::write_stash_stack(void_dir, key, &stack).map_err(void_err_to_cli)?;

    let message = entry.message.clone();
    let original_head_str = cid::from_bytes(entry.original_head.as_bytes())
        .map(|c| c.to_string())
        .unwrap_or_else(|_| hex::encode(entry.original_head.as_bytes()));

    // Human-readable output
    if !ctx.use_json() {
        ctx.info(format!("Applied stash@{{{}}}", index));
        if let Some(ref msg) = message {
            ctx.info(format!("  {}", msg));
        }
    }

    Ok(StashOutput {
        action: "pop".to_string(),
        entries: None,
        index: Some(index),
        commit_cid: None,
        original_head: Some(original_head_str),
        message,
        count: None,
    })
}

/// Drop a stash entry without applying.
fn run_drop(
    ctx: &mut crate::output::CommandContext,
    void_dir: &Path,
    key: &SecretKey,
    index: u32,
) -> Result<StashOutput, CliError> {
    ctx.progress(format!("Dropping stash@{{{}}}...", index));

    let mut stack = stash::read_stash_stack(void_dir, key).map_err(void_err_to_cli)?;

    let entry = stack
        .get(index)
        .cloned()
        .ok_or_else(|| CliError::not_found(format!("stash@{{{}}} not found", index)))?;

    let message = entry.message.clone();

    // Remove from stash stack
    stack.remove(index);
    stash::write_stash_stack(void_dir, key, &stack).map_err(void_err_to_cli)?;

    // Human-readable output
    if !ctx.use_json() {
        ctx.info(format!("Dropped stash@{{{}}}", index));
    }

    Ok(StashOutput {
        action: "drop".to_string(),
        entries: None,
        index: Some(index),
        commit_cid: None,
        original_head: None,
        message,
        count: None,
    })
}

/// Clear all stash entries.
fn run_clear(
    ctx: &mut crate::output::CommandContext,
    void_dir: &Path,
    key: &SecretKey,
) -> Result<StashOutput, CliError> {
    ctx.progress("Clearing stash...");

    let stack = stash::read_stash_stack(void_dir, key).map_err(void_err_to_cli)?;
    let count = stack.len();

    stash::clear_stash(void_dir, key).map_err(void_err_to_cli)?;

    // Human-readable output
    if !ctx.use_json() {
        if count == 0 {
            ctx.info("Stash already empty.");
        } else {
            ctx.info(format!(
                "Cleared {} stash {}",
                count,
                if count == 1 { "entry" } else { "entries" }
            ));
        }
    }

    Ok(StashOutput {
        action: "clear".to_string(),
        entries: None,
        index: None,
        commit_cid: None,
        original_head: None,
        message: None,
        count: Some(count),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::CliOptions;
    use std::fs;
    use tempfile::tempdir;
    use void_core::crypto;

    fn default_opts() -> CliOptions {
        CliOptions {
            human: true,
            ..Default::default()
        }
    }

    fn setup_test_repo() -> (tempfile::TempDir, std::path::PathBuf, tempfile::TempDir, crate::context::VoidHomeGuard) {
        let dir = tempdir().unwrap();
        let void_dir = dir.path().join(".void");
        fs::create_dir_all(void_dir.join("objects")).unwrap();
        fs::create_dir_all(void_dir.join("refs/heads")).unwrap();

        // Create key and manifest
        let key = crypto::generate_key();
        let home = tempdir().unwrap();
        let guard = crate::context::setup_test_manifest(&void_dir, &key, home.path());

        // Create config file with repoSecret
        let repo_secret = hex::encode(crypto::generate_key());
        fs::write(
            void_dir.join("config.json"),
            format!(r#"{{"repoSecret": "{}"}}"#, repo_secret),
        )
        .unwrap();

        // Create a test file
        fs::write(dir.path().join("test.txt"), "hello world").unwrap();

        (dir, void_dir, home, guard)
    }

    #[test]
    fn test_stash_list_empty() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        let args = StashArgs {
            action: StashAction::List,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_ok());
    }

    #[test]
    fn test_stash_clear_empty() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        let args = StashArgs {
            action: StashAction::Clear,
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_ok());
    }

    #[test]
    fn test_stash_drop_not_found() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        let args = StashArgs {
            action: StashAction::Drop { index: Some(5) },
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
    }

    #[test]
    fn test_stash_pop_not_found() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        let args = StashArgs {
            action: StashAction::Pop { index: Some(0) },
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
    }

    #[test]
    fn test_stash_save_no_head() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();

        // No HEAD set, so stash save should fail
        let args = StashArgs {
            action: StashAction::Save {
                message: Some("test".to_string()),
            },
        };

        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
    }

    #[test]
    fn test_format_relative_time() {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        assert_eq!(format_relative_time(now), "just now");
        assert_eq!(format_relative_time(now - 120), "2 minutes ago");
        assert_eq!(format_relative_time(now - 3600), "1 hour ago");
        assert_eq!(format_relative_time(now - 7200), "2 hours ago");
        assert_eq!(format_relative_time(now - 86400), "1 day ago");
        assert_eq!(format_relative_time(now - 172800), "2 days ago");
        assert_eq!(format_relative_time(now - 604800), "1 week ago");
    }

    #[test]
    fn test_stash_output_serialization() {
        let output = StashOutput {
            action: "list".to_string(),
            entries: Some(vec![StashEntryOutput {
                index: 0,
                commit_cid: "bafytest123".to_string(),
                original_head: "bafyhead456".to_string(),
                message: Some("WIP".to_string()),
                timestamp: 1234567890,
            }]),
            index: None,
            commit_cid: None,
            original_head: None,
            message: None,
            count: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"action\":\"list\""));
        assert!(json.contains("\"entries\""));
        assert!(json.contains("\"message\":\"WIP\""));
        // Entry has index, but top-level index should be None (not serialized at top level)
        // The JSON will have index inside entries array, which is expected
        assert!(!json.contains("\"count\""));
        // Verify the top-level structure doesn't have an "index" key at the same level as "action"
        // by checking that index only appears inside entries
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.get("index").is_none());
    }

    #[test]
    fn test_save_output_serialization() {
        let output = StashOutput {
            action: "save".to_string(),
            entries: None,
            index: Some(0),
            commit_cid: Some("bafytest123".to_string()),
            original_head: None,
            message: Some("my stash".to_string()),
            count: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"action\":\"save\""));
        assert!(json.contains("\"index\":0"));
        assert!(json.contains("\"message\":\"my stash\""));
        assert!(json.contains("\"commitCid\":\"bafytest123\""));
        assert!(!json.contains("\"entries\""));
    }

    #[test]
    fn test_clear_output_serialization() {
        let output = StashOutput {
            action: "clear".to_string(),
            entries: None,
            index: None,
            commit_cid: None,
            original_head: None,
            message: None,
            count: Some(3),
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"action\":\"clear\""));
        assert!(json.contains("\"count\":3"));
        assert!(!json.contains("\"entries\""));
        assert!(!json.contains("\"index\""));
    }
}