casq 0.8.2

A minimal content-addressed file store using BLAKE3. (CLI)
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# `casq`

A content-addressed file store CLI with compression and chunking (v0.4.0).

This is Alpha level software.

## Overview

**`casq`** is a command-line tool for managing content-addressed storage. It stores files and directories by their cryptographic hash, providing automatic deduplication, transparent compression, content-defined chunking, garbage collection, and named references.

This is the CLI binary that uses the `casq_core` library.

## Installation

```bash
# Build from source
cargo build --release -p casq

# The binary will be at target/release/casq
# Install it by
cargo install --path ./casq
# Optionally, copy to your PATH
cp target/release/casq $HOME/.local/bin/
```

## Quick Start

```bash
# Initialize a new store
casq initialize

# Add files or directories
casq put myfile.txt
casq put mydir/

# Add content from stdin (pipe data directly) - in most cases you want to use --reference
curl https://example.org | casq put --reference example-dot-org@20260123 -
echo "quick note" | casq put --reference note-123 -

# Add with a named reference
casq put important-data/ --reference backup-2024

# Discover what content you have
casq references list              # Lists all references

# List tree contents (requires hash)
casq list <hash>

# Output blob content
casq get <hash>

# Show object metadata
casq metadata <hash>

# Materialize (restore) to filesystem
casq materialize <hash> ./restored

# Garbage collect unreferenced objects
casq collect-garbage --dry-run  # Preview
casq collect-garbage            # Actually delete
```

## Commands

### `casq initialize`

Initialize a new content-addressed store.

```bash
casq initialize [--algorithm blake3]

Options:
  -a, --algorithm <ALGORITHM>  Hash algorithm (default: blake3)
```

Creates the store directory structure at the configured root (default: `./casq-store`).

### `casq put <PATH>` or `casq put -`

Add files, directories, or stdin content to the store.

```bash
casq put <PATH> [--reference <NAME>]
casq put - [--reference <NAME>]

Arguments:
  <PATH>  Path to add (a single file or directory), or
  -       Read content from stdin

Options:
  --reference <NAME>  Create a named reference to the added content
```

**Examples:**

```bash
# Add a single file
casq put document.pdf

# Add a directory
casq put project/

# Add with a reference
casq put project/ --reference release-v1.0

# Add from stdin
echo "Hello, World!" | casq put -
curl https://api.example.com/data | casq put --reference api-snapshot -
cat large-file.bin | casq put --reference binary-data -
```

The command outputs the hash of the added object. Directories are added recursively and stored as tree objects (and the returned hash is that of the tree itself). Stdin content is stored as a blob.

**Important notes:**
- Output format on stdout is: `<hash>`

### `casq materialize <HASH> <DEST>`

Materialize (restore) an object from the store to the filesystem.

```bash
casq materialize <HASH> <DEST>

Arguments:
  <HASH>  Hash of the object to materialize
  <DEST>  Destination path (must not exist)
```

**Examples:**

```bash
# Restore a directory
casq materialize abc123... ./restored-project

# Restore a file
casq materialize def456... ./document.pdf
```

### `casq get <HASH>`

Output blob content to stdout.

```bash
casq get <HASH>

Arguments:
  <HASH>  Hash of the blob
```

**Examples:**

```bash
# View a text file
casq get abc123...

# Pipe to another command
casq get abc123... | grep "search term"

# Save to a file
casq get abc123... > output.txt
```

### `casq list <HASH>`

List tree contents or show blob info.

```bash
casq list <HASH> [--long]

Arguments:
  <HASH>  Hash of the object (required)

Options:
  -l, --long  Show detailed information
```

**Examples:**

```bash
# List directory contents
casq list abc123...

# Show detailed listing with modes and hashes
casq list --long abc123...

# Output format (short):
# filename.txt
# subdir

# Output format (--long):
# b 100644 <hash> filename.txt
# t 040755 <hash> subdir
```

Type codes: `b` = blob (file), `t` = tree (directory)

**Tip:** Use `casq references list` to discover content, then `casq list <hash>` to explore it.

### `casq metadata <HASH>`

Show detailed metadata about an object.

```bash
casq metadata <HASH>

Arguments:
  <HASH>  Hash of the object
```

**Example output:**

```
Hash: abc123...
Type: tree
Entries: 5
Size: 320 bytes (on disk)
Path: ./casq-store/objects/blake3-256/ab/c123...
```

### `casq collect-garbage`

Garbage collect unreferenced objects.

```bash
casq collect-garbage [--dry-run]

Options:
  --dry-run  Show what would be deleted without actually deleting
```

**Examples:**

```bash
# Preview what would be deleted
casq collect-garbage --dry-run

# Actually delete unreferenced objects
casq collect-garbage
```

Walks from all named references and deletes objects that are no longer reachable.

### `casq references add <NAME> <HASH>`

Add a named reference to an object.

```bash
casq references add <NAME> <HASH>

Arguments:
  <NAME>  Reference name
  <HASH>  Hash to reference
```

**Examples:**

```bash
casq references add backup-2024 abc123...
casq references add important def456...
```

References act as GC roots - objects reachable from references won't be deleted by `collect-garbage`.

### `casq references list`

List all references.

```bash
casq references list
```

**Example output:**

```
backup-2024 -> abc123...
important -> def456...
```

### `casq references remove <NAME>`

Remove a reference.

```bash
casq references remove <NAME>

Arguments:
  <NAME>  Reference name to remove
```

**Example:**

```bash
casq references remove old-backup
```

## Global Options

All commands support these global options:

```bash
-r, --root <ROOT>  Store root directory
-h, --help         Print help
-V, --version      Print version
```

### Store Root Priority

The store root is determined in this order:

1. `--root` CLI argument
2. `CASQ_ROOT` environment variable
3. `./casq-store` (default)

**Examples:**

```bash
# Use explicit root
casq --root /backup/store put myfile.txt

# Use environment variable
export CASQ_ROOT=/backup/store
casq put myfile.txt

# Use default (./casq-store)
casq put myfile.txt
```

## Output Streams

`casq` follows Unix conventions for output streams to enable proper pipeline usage:

**Text mode** (default):
- All informational messages, confirmations, and data → **stderr**
- **stdout** is empty
- This allows reliable pipeline usage and scripting

**JSON mode** (`--json` flag):
- All structured output → **stdout**
- Errors → **stderr** (as JSON)
- Designed for parsing and automation

**Examples:**

```bash
# Text mode - output on stderr
casq put file.txt                  # Extract hash
casq references list | grep myref  # Filter refs

# Suppress informational messages
casq initialize 2>/dev/null

# JSON mode - output on stdout (recommended for scripts)
HASH=$(casq --json put file.txt | jq -r '.object.hash')
casq --json references list | jq '.refs[].name
```

**For scripting**: Use `--json` flag for reliable, machine-readable output.

## Typical Workflows

### Backup Workflow

```bash
# Initialize store
casq initialize

# Create initial backup
casq put ~/important-data --reference backup-$(date +%Y%m%d)

# Add more data later
casq put ~/important-data --reference backup-$(date +%Y%m%d)

# List all backups
casq references list

# Restore a backup
casq materialize <hash> ~/restored-data

# Clean up old backups
casq references remove backup-20240101
casq collect-garbage
```

### Deduplication Example

```bash
# Add the same file twice
casq put file.txt
# Output: abc123...

casq put file.txt
# Output: abc123... (same hash - deduplicated!)

# Only one copy stored internally
```

### Exploring Content

```bash
# Add a directory with a reference
casq put myproject/ --reference current-work

# Discover what's in your store
casq references list
# Output: current-work -> abc123...

# Explore the tree
HASH=$(casq references list --json | jq '.[0].name')
casq list $HASH

# Look at a specific file
FILE_HASH=$(casq list --json --long $HASH | jq '.entries[] | select(.name == "README.md") | .hash' )
casq get $FILE_HASH
```

## Store Structure

```
casq-store/
├── config                    # Store configuration
├── objects/
│   └── blake3-256/          # Algorithm-specific directory
│       ├── ab/              # Shard directory (first 2 hex chars)
│       │   └── cd...ef      # Object file (remaining 62 hex chars)
│       └── ...
└── refs/                    # Named references
    ├── backup-2024
    └── important
```

## Object Types

- **Blob** - Raw file content (automatically compressed if ≥ 4KB)
- **Tree** - Directory listing (sorted entries)
- **ChunkList** - Large file split into chunks (files ≥ 1MB, enables incremental backups)

Trees reference other blobs and trees, forming a hierarchical structure similar to git. Large files are split into chunks for efficient incremental backups and cross-file deduplication.

## Exit Codes

- `0` - Success
- `1` - Error (with descriptive message to stderr)

## Environment Variables

- `CASQ_ROOT` - Default store root directory

## Error Handling

All commands provide clear error messages:

```bash
$ casq get invalid-hash
Error: Invalid hash: invalid-hash

$ casq put /nonexistent
Error: Failed to add path: /nonexistent
Caused by:
    No such file or directory (os error 2)
```

## Performance Tips

1. **Large files** - Content is streamed, not buffered in memory
2. **Many small files** - Use directories to group them
3. **Deduplication** - Identical content is stored only once (including chunk-level deduplication)
4. **Compression** - Files ≥ 4KB automatically compressed with zstd (3-5x typical reduction)
5. **Chunking** - Files ≥ 1MB split into chunks for incremental backups (change 1 byte → store ~512KB)
6. **GC frequency** - Run `gc` periodically to reclaim space from unreferenced objects

## Storage Efficiency (v0.4.0+)

- **Compression**: 3-5x reduction for text files, 2-3x for mixed data
- **Chunking**: Change 1 byte in 1GB file → store only ~512KB (changed chunk)
- **Cross-file deduplication**: Shared content across files stored only once
- **Example**: 10 files with identical 5MB section = 5MB stored (not 50MB)

## JSON Output

All commands support the `--json` flag for machine-readable output, enabling scripting and automation.

### Basic Usage

```bash
# Get JSON output from any command
casq --json initialize
casq --json put myfile.txt
casq --json references list
casq --json collect-garbage --dry-run

# Pipe through jq for processing
casq --json references list | jq '.refs[].name'
casq --json put file.txt | jq '.object.hash'
```

### Standard Response Format

All JSON responses include these standard fields:
- `success` (boolean) - Whether the operation succeeded
- `result_code` (number) - Exit code (0 for success, non-zero for errors)

### Command-Specific Outputs

#### `initialize`
```json
{
  "success": true,
  "result_code": 0,
  "root": "/path/to/store",
  "algorithm": "blake3-256"
}
```

#### `put`
```json
{
  "success": true,
  "result_code": 0,
  "objects": [
    {"hash": "abc123...", "path": "/path/to/file.txt"}
  ],
  "reference": {
    "name": "myref",
    "hash": "abc123..."
  }
}
```

#### `references list`
```json
{
  "success": true,
  "result_code": 0,
  "type": "RefList",
  "refs": [
    {"name": "backup", "hash": "abc123..."}
  ]
}
```

#### `list <hash>` (tree contents)
```json
{
  "success": true,
  "result_code": 0,
  "type": "TreeContents",
  "hash": "abc123...",
  "entries": [
    {
      "name": "file.txt",
      "entry_type": "blob",
      "mode": "100644",
      "hash": "def456..."
    }
  ]
}
```

#### `metadata <hash>` (blob)
```json
{
  "success": true,
  "result_code": 0,
  "type": "Blob",
  "hash": "abc123...",
  "size": 1024,
  "size_on_disk": 512,
  "path": "/store/objects/blake3-256/ab/c123..."
}
```

#### `collect-garbage`
```json
{
  "success": true,
  "result_code": 0,
  "dry_run": false,
  "objects_deleted": 42,
  "bytes_freed": 1048576
}
```

#### `find-orphans`
```json
{
  "success": true,
  "result_code": 0,
  "orphans": [
    {
      "hash": "abc123...",
      "entry_count": 15,
      "approx_size": 1024
    }
  ]
}
```

#### Error Response (stderr)
```json
{
  "success": false,
  "result_code": 1,
  "error": "Object not found: abc123..."
}
```

### Scripting Examples

```bash
# Extract hash from put operation
HASH=$(casq --json put data.txt | jq -r '.objects[0].hash')

# Count orphaned objects
COUNT=$(casq --json find-orphans | jq '.orphans | length')

# List all reference names
casq --json references list | jq -r '.refs[].name'

# Get GC stats
casq --json collect-garbage --dry-run | jq '{objects:.objects_deleted, bytes:.bytes_freed}'

# Check if operation succeeded
if casq --json put file.txt | jq -e '.success' > /dev/null; then
  echo "Success"
else
  echo "Failed"
fi
```

### Exit Codes

Program exit codes match the `result_code` field in JSON output:
- `0` - Success
- `1` - Error (details in `error` field for JSON, or stderr for text)

### Binary Data Limitation

The `get` command outputs binary data to stdout and cannot be used with `--json`. Use `materialize` or `metadata` instead:

```bash
# This will error with JSON
casq --json get <hash>  # Error: binary data incompatible with JSON

# Use these alternatives
casq --json materialize <hash> ./output  # Save to file
casq --json metadata <hash>              # Get metadata
```

## Limitations

- **No encryption** - Store plaintext only
- **No network** - Local-only storage
- **No parallel operations** - Single-threaded (may be added in future)
- **POSIX only** - Full permission preservation only on Unix-like systems

## Comparison to Git

| Feature            | casq         | Git             |
|--------------------|--------------|-----------------|
| Content addressing |||
| Deduplication      |||
| Trees/Blobs        |||
| Hash algorithm     | BLAKE3       | SHA-1/SHA-256   |
| Commits            |||
| Branches           |||
| Diffs              |||
| Network            |||
| Use case           | File storage | Version control |

casq is simpler than git - it's just content-addressed storage without the version control features.

## Troubleshooting

### Store not found

```bash
$ casq put file.txt
Error: Failed to open store at ./casq-store

# Solution: Initialize the store first
$ casq initialize
```

### Object not found

```bash
$ casq get abc123...
Error: Object not found: abc123...

# Solution: Verify the hash is correct
$ casq references list  # Find the correct hash
```

### Path already exists

```bash
$ casq materialize abc123... ./output
Error: Path already exists: ./output

# Solution: Remove the destination first or use a different path
$ rm -rf ./output
$ casq materialize abc123... ./output
```

## Development

```bash
# Run from source
cargo run -p casq -- <args>

# Build optimized binary
cargo build --release -p casq

# Run tests
cargo test -p casq

# Format code
cargo fmt -p casq

# Lint
cargo clippy -p casq
```

## License

> Apache-2.0

## See Also

- [**casq_core**]https://crates.io/crates/casq_core - The library powering this CLI
- **NOTES.md** - Design and specification
- **CLAUDE.md** - Development guidelines