koru-delta 2.0.0

The invisible database: causal, consistent, and everywhere—without configuration
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
# KoruDelta CLI Guide

Complete guide to using the `kdelta` command-line tool.

## Installation

### From Source

```bash
cargo install --path .
```

Or build the binary:

```bash
cargo build --release
# Binary will be at: target/release/kdelta
```

## Quick Start

```bash
# Store data
kdelta set users/alice '{"name": "Alice", "age": 30}'

# Retrieve data
kdelta get users/alice

# View history
kdelta log users/alice

# Show database statistics
kdelta status
```

## Commands

### `kdelta set` - Store a Value

Store JSON data in the database.

**Format:**
```bash
kdelta set <namespace>/<key> <value>
```

**Examples:**

```bash
# Store a user object
kdelta set users/alice '{"name": "Alice", "age": 30, "email": "alice@example.com"}'

# Store a simple number
kdelta set counters/visits 42

# Store a string (must be valid JSON)
kdelta set config/theme '"dark"'

# Store an array
kdelta set tags/favorites '["rust", "database", "distributed"]'

# Store nested objects
kdelta set profiles/alice '{
  "name": "Alice",
  "settings": {
    "theme": "dark",
    "notifications": true
  }
}'
```

**Output:**
```
✓
  Stored: users/alice
  Version: 3312c469326df7ef845afecc14c1a22d4e2a46091a8c9e14b1b66f279f524aea
  Timestamp: 2025-11-24 17:00:22 UTC
```

**Notes:**
- Values must be valid JSON
- Strings must be quoted: `'"value"'` not `'value'`
- Updates create new versions (doesn't overwrite history)
- Data is automatically persisted to disk

### `kdelta get` - Retrieve a Value

Retrieve the current value for a key.

**Format:**
```bash
kdelta get <namespace>/<key> [--verbose]
```

**Examples:**

```bash
# Get a value
kdelta get users/alice

# Get with metadata
kdelta get users/alice --verbose
kdelta get users/alice -v
```

**Output (normal):**
```json
{
  "age": 30,
  "name": "Alice"
}
```

**Output (verbose):**
```json
{
  "age": 30,
  "name": "Alice"
}

Metadata:
  Version: 3312c469326df7ef845afecc14c1a22d4e2a46091a8c9e14b1b66f279f524aea
  Timestamp: 2025-11-24 17:00:22 UTC
  Previous: a1b2c3d4...
```

**Error Handling:**
```bash
$ kdelta get users/nonexistent
✗
  Key not found: users/nonexistent
```

### `kdelta log` - View History

Show the complete change history for a key.

**Format:**
```bash
kdelta log <namespace>/<key> [--limit N]
```

**Examples:**

```bash
# Show all history
kdelta log users/alice

# Show last 5 changes
kdelta log users/alice --limit 5
kdelta log users/alice -l 5
```

**Output:**
```
History:

  ● 2025-11-24 17:01:03 UTC
    {
  "age": 31,
  "city": "SF",
  "name": "Alice"
}
    Version: debcd55b6a671c4d2b8c06155a890f1c8d0d4aebac8b70d86d4b7e4fde931f08

  ● 2025-11-24 17:00:22 UTC
    {
  "age": 30,
  "name": "Alice"
}
    Version: 3312c469326df7ef845afecc14c1a22d4e2a46091a8c9e14b1b66f279f524aea

  2 versions total
```

**Notes:**
- History is shown in reverse chronological order (newest first)
- Each entry shows the full value at that point in time
- Version IDs are content-addressed (SHA256 hashes)

### `kdelta diff` - Compare Versions

Show differences between two versions of a key.

**Format:**
```bash
kdelta diff <namespace>/<key> [OPTIONS]
```

**Options:**
- `--at <timestamp>` - Compare value at timestamp with its previous version
- `--from <index>` - Compare from this version index (0 = oldest)
- `--to <index>` - Compare to this version index

**Examples:**

```bash
# Compare latest version with previous (default)
kdelta diff users/alice

# Compare value at specific timestamp with its previous version
kdelta diff users/alice --at "2025-11-24T17:00:00Z"

# Compare specific version indices (0 = oldest)
kdelta diff users/alice --from 0 --to 2
```

**Output:**
```
Comparing versions:

  − Version 1 (2025-11-24 17:23:23 UTC)
  + Version 2 (2025-11-24 17:23:23 UTC)

Diff:

  − Version 1
  + Version 2

    {
      "age": 31,
      "city": "SF",
  −   "name": "Alice",
  +   "name": "Alice Smith",
      "skills": [
        "rust",
  −     "python"
  +     "python",
  +     "go"
      ]
    }
```

**Notes:**
- Red lines (−) show deletions from the old version
- Green lines (+) show additions in the new version
- Gray lines show unchanged content
- Uses line-by-line diff algorithm for JSON values

### `kdelta status` - Database Statistics

Show information about the database.

**Format:**
```bash
kdelta status
```

**Output:**
```
Database Status

  Keys: 3
  Versions: 4
  Namespaces: 2

Namespaces:
  ● counters (1 key)
  ● users (2 keys)

  Database: /Users/sawyerkent/.korudelta/db
```

**Information Shown:**
- Total number of unique keys
- Total number of versions (including history)
- Number of namespaces
- List of namespaces with key counts
- Database file location

### `kdelta list` - List Namespaces or Keys

List all namespaces, or list keys within a namespace.

**Format:**
```bash
kdelta list [namespace]
```

**Examples:**

```bash
# List all namespaces
kdelta list

# List keys in a namespace
kdelta list users
```

**Output (list all):**
```
Namespaces:

  ● counters (1 key)
  ● users (2 keys)
```

**Output (list users):**
```
Keys in 'users':

  ● users/alice
  ● users/bob
```

### `kdelta query` - Query Engine

Execute filtered, sorted, and aggregated queries.

**Format:**
```bash
kdelta query <namespace> [OPTIONS]
```

**Options:**
- `-f, --filter <expr>` - Filter expression
- `-s, --sort <field>` - Sort field
- `--desc` - Sort descending
- `-l, --limit <n>` - Limit results
- `-c, --count` - Count only (no data)

**Filter Syntax:**
- `field = "value"` - Equality
- `field != "value"` - Not equal
- `field > 10` - Greater than
- `field >= 10` - Greater or equal
- `field < 10` - Less than
- `field <= 10` - Less or equal
- `field ~ "pattern"` - Contains substring

**Examples:**

```bash
# Query all users
kdelta query users

# Filter active users
kdelta query users --filter 'status = "active"'

# Filter with multiple conditions (AND)
kdelta query users --filter 'age > 30' --filter 'status = "active"'

# Sort and limit
kdelta query users --sort age --desc --limit 10

# Count only
kdelta query users --filter 'status = "active"' --count
```

**Output:**
```
Query results: (2 records)

  ● alice
    {
      "age": 30,
      "name": "Alice",
      "status": "active"
    }
  ● bob
    {
      "age": 35,
      "name": "Bob",
      "status": "active"
    }
```

### `kdelta view` - Materialized Views

Create and manage materialized views for cached query results.

**Subcommands:**
- `view create <name> <source> [OPTIONS]` - Create a new view
- `view list` - List all views
- `view query <name>` - Query a view
- `view refresh <name>` - Manually refresh a view
- `view delete <name>` - Delete a view

**Create Options:**
- `-f, --filter <filter>` - Filter expression (e.g., 'status = "active"')
- `-s, --sort <field>` - Sort field
- `--desc` - Sort descending
- `-d, --description <text>` - View description

**Examples:**

```bash
# Create a view of active users
kdelta view create active_users users --filter 'status = "active"'

# Create with description and sorting
kdelta view create premium_customers users \
  --filter 'tier = "premium"' \
  --sort created_at --desc \
  --description "High-value customers"

# List all views
kdelta view list

# Query a view (instant, cached results)
kdelta view query active_users

# Refresh view (auto-refreshes on writes by default)
kdelta view refresh active_users

# Delete a view
kdelta view delete active_users
```

**View Output:**
```
View 'active_users' results: (42 records)

  ● alice
    {
      "name": "Alice",
      "status": "active"
    }
  ● bob
    {
      "name": "Bob",
      "status": "active"
    }
```

**Notes:**
- Views persist across database restarts
- Auto-refresh on writes (can be disabled)
- Filter syntax: `field = "value"`, `field > 10`, `field != null`
- Views are stored in the `__views` namespace

### `kdelta serve` - HTTP API Server

Start an HTTP server that exposes the KoruDelta API over REST for remote clients.

**Usage:**
```bash
kdelta serve [OPTIONS]
```

**Options:**
- `-p, --port <PORT>` - Port to listen on (default: 8080)
- `-b, --bind <ADDR>` - Address to bind to (default: 0.0.0.0)

**Examples:**

```bash
# Start HTTP server on default port 8080
kdelta serve

# Start on custom port
kdelta serve --port 3000

# Bind to localhost only
kdelta serve --bind 127.0.0.1

# Custom port and bind address
kdelta serve -p 8080 -b 0.0.0.0
```

**API Endpoints:**
- `GET /health` - Health check
- `GET /api/v1/keys/{namespace}/{key}` - Get value
- `POST /api/v1/keys/{namespace}/{key}` - Set value
- `GET /api/v1/namespaces/{namespace}` - List keys in namespace
- `GET /api/v1/namespaces` - List all namespaces

**Use Cases:**
- Remote database access
- Multi-language clients
- Web application backends

### `kdelta watch` - Real-time Subscriptions

Watch for changes in real-time. Subscribe to namespaces or specific keys and receive notifications.

**Usage:**
```bash
kdelta watch [TARGET] [OPTIONS]
```

**Arguments:**
- `TARGET` - Namespace or namespace/key to watch (optional)

**Options:**
- `--all` - Watch all changes across all namespaces
- `--inserts-only` - Only show insert operations
- `--updates-only` - Only show update operations

**Examples:**

```bash
# Watch all changes in a namespace
kdelta watch users

# Watch a specific key
kdelta watch users/alice

# Watch all changes in the database
kdelta watch --all

# Only watch for new inserts
kdelta watch users --inserts-only

# Only watch for updates
kdelta watch users --updates-only
```

**Output:**
```
● Insert in users: bob
  {"name": "Bob", "role": "user"}

● Update in users: alice
  {"name": "Alice", "role": "admin"}
```

**Notes:**
- Runs until interrupted (Ctrl+C)
- Shows change type (Insert, Update, Delete)
- Displays the new value after change

### `kdelta auth` - Authentication & Authorization

Manage self-sovereign identities and capability-based access control.

**Subcommands:**
- `auth create` - Create a new identity
- `auth list` - List all identities
- `auth grant` - Grant a capability to another identity
- `auth list-caps` - List capabilities for current identity
- `auth revoke` - Revoke a capability

#### `kdelta auth create`

Create a new identity with Ed25519 keypair and proof-of-work.

**Usage:**
```bash
kdelta auth create [OPTIONS]
```

**Options:**
- `-n, --name <NAME>` - Display name for the identity

**Example:**
```bash
# Create identity with name
kdelta auth create --name "Alice Admin"

# Create anonymous identity
kdelta auth create
```

**Output:**
```
Identity created: did:koru:abc123...
Public Key: ed25519:xyz789...
Name: Alice Admin
```

#### `kdelta auth list`

List all identities stored in the database.

**Usage:**
```bash
kdelta auth list
```

**Example:**
```bash
kdelta auth list
```

**Output:**
```
Identities: (2)

● did:koru:abc123...
  Name: Alice Admin
  Created: 2026-02-09T10:00:00Z

● did:koru:def456...
  Name: Bob User
  Created: 2026-02-09T11:00:00Z
```

#### `kdelta auth grant`

Grant a capability to another identity.

**Usage:**
```bash
kdelta auth grant --to <IDENTITY> --resource <PATTERN> --permission <LEVEL> [OPTIONS]
```

**Options:**
- `-t, --to <IDENTITY>` - Identity to grant capability to (required)
- `-r, --resource <PATTERN>` - Resource pattern (e.g., "users/*", "documents:file1") (required)
- `-p, --permission <LEVEL>` - Permission level: read, write, or admin (required)
- `-e, --expires <DURATION>` - Expiration time (e.g., "1h", "1d", "7d")

**Examples:**

```bash
# Grant read access to all users
kdelta auth grant \
  --to did:koru:abc123... \
  --resource "users/*" \
  --permission read

# Grant write access with 1-day expiration
kdelta auth grant \
  --to did:koru:abc123... \
  --resource "documents/*" \
  --permission write \
  --expires 1d

# Grant admin access to specific resource
kdelta auth grant \
  --to did:koru:abc123... \
  --resource "config:settings" \
  --permission admin
```

**Resource Patterns:**
- `users/*` - All keys in users namespace
- `documents:file1` - Specific key
- `config:*` - All config keys
- `*` - All resources (admin only)

#### `kdelta auth list-caps`

List capabilities granted to the current identity.

**Usage:**
```bash
kdelta auth list-caps
```

**Example:**
```bash
kdelta auth list-caps
```

**Output:**
```
Capabilities: (3)

● cap_abc123...
  Resource: users/*
  Permission: read
  Granted by: did:koru:xyz789...
  Expires: Never

● cap_def456...
  Resource: documents/*
  Permission: write
  Granted by: did:koru:xyz789...
  Expires: 2026-02-10T10:00:00Z
```

#### `kdelta auth revoke`

Revoke a previously granted capability.

**Usage:**
```bash
kdelta auth revoke --capability <CAPABILITY_ID>
```

**Options:**
- `-c, --capability <ID>` - Capability ID to revoke (required)

**Example:**
```bash
# Revoke a capability
kdelta auth revoke --capability cap_abc123...
```

**Notes:**
- You can only revoke capabilities you granted
- Revocation creates a tombstone (auditable)
- Revoked capabilities are immediately invalidated

## Global Options

### `--db-path` - Custom Database Location

By default, `kdelta` stores data in `~/.korudelta/db`. You can specify a custom location:

```bash
# Use custom database file
kdelta --db-path /tmp/mydb.json set test/key '{"value": 1}'
kdelta --db-path /tmp/mydb.json get test/key

# Short form
kdelta -d /tmp/mydb.json status
```

**Use Cases:**
- Multiple independent databases
- Testing without affecting main database
- Project-specific databases
- Temporary databases

## Key Format

Keys in KoruDelta use the format `namespace/key`.

### Namespace

A logical grouping of related data (similar to tables or collections):

- `users` - User data
- `sessions` - Session information
- `config` - Configuration
- `counters` - Numeric counters
- `cache` - Cached data

### Key

Unique identifier within the namespace:

- `alice`, `bob`, `charlie` - User IDs
- `app`, `database`, `logging` - Config keys
- `visits`, `clicks`, `errors` - Counter names

### Examples

```bash
users/alice          # User alice
users/bob            # User bob
sessions/xyz123      # Session xyz123
config/app           # App config
counters/visits      # Visit counter
cache/user:123       # Cached user data
```

**Naming Guidelines:**
- Use lowercase for consistency
- Avoid special characters (stick to alphanumeric, dash, underscore)
- Use descriptive names
- Keep namespace names short and key names specific

## Data Persistence

### Automatic Saving

Data is automatically saved to disk after every `set` operation. No manual save command needed.

### Database Location

**Default:** `~/.korudelta/db`

**Custom:** Use `--db-path` flag

### Format

Data is stored as JSON (human-readable):

```bash
# You can inspect the database file directly
cat ~/.korudelta/db | jq '.'
```

**Structure:**
```json
{
  "version": 1,
  "current_state": [...],
  "history_log": [...]
}
```

## Advanced Usage

### Multiple Databases

```bash
# Development database
kdelta -d ~/dev.db set test/key '1'

# Production database
kdelta -d ~/prod.db set test/key '2'

# Testing database
kdelta -d /tmp/test.db set test/key '3'
```

### Scripting

```bash
#!/bin/bash

# Store metrics
for i in {1..100}; do
  kdelta set counters/visits "$i"
done

# Read and process
kdelta get counters/visits | jq '.value'
```

### Backup and Restore

```bash
# Backup
cp ~/.korudelta/db ~/backup/korudelta-$(date +%Y%m%d).db

# Restore
cp ~/backup/korudelta-20251124.db ~/.korudelta/db
```

### Querying History Programmatically

```bash
# Get all history as JSON
kdelta log users/alice --limit 1000 > history.txt

# Process with jq or other tools
# (Note: Current output is human-readable, not JSON)
```

## Performance Tips

### Batch Operations

For better performance when inserting many keys:

```bash
# Shell loop (automatic persistence)
for i in {1..1000}; do
  kdelta set items/item$i "{\"id\": $i}"
done
```

### Large Values

KoruDelta handles JSON of any size, but keep in mind:
- Larger values → longer serialization time
- All history is kept (consider data lifecycle)

## Troubleshooting

### "Invalid JSON value"

**Problem:** Value isn't valid JSON

**Solution:**
```bash
# Wrong: bare strings aren't valid JSON
kdelta set config/name hello  # ✗ Error

# Right: strings must be quoted
kdelta set config/name '"hello"'  # ✓ Works
```

### "Invalid key format"

**Problem:** Key doesn't follow `namespace/key` format

**Solution:**
```bash
# Wrong: missing namespace
kdelta set mykey '{"value": 1}'  # ✗ Error

# Right: includes namespace
kdelta set data/mykey '{"value": 1}'  # ✓ Works
```

### "Key not found"

**Problem:** Trying to get a key that doesn't exist

**Solution:**
```bash
# Check if key exists first
kdelta list mynamespace

# Or handle error in scripts
kdelta get myns/mykey || echo "Key not found"
```

## Examples & Recipes

### User Management

```bash
# Create users
kdelta set users/alice '{"name": "Alice", "role": "admin"}'
kdelta set users/bob '{"name": "Bob", "role": "user"}'

# List all users
kdelta list users

# Get user details
kdelta get users/alice

# Update user
kdelta set users/alice '{"name": "Alice", "role": "superadmin"}'

# View change history
kdelta log users/alice
```

### Configuration Management

```bash
# Set configuration
kdelta set config/database '{"host": "localhost", "port": 5432}'
kdelta set config/cache '{"ttl": 3600, "max_size": 1000}'

# Read config
kdelta get config/database | jq '.host'

# Update config
kdelta set config/database '{"host": "db.example.com", "port": 5432}'
```

### Counters and Metrics

```bash
# Initialize counter
kdelta set metrics/requests 0

# Increment (requires reading, incrementing, and writing)
requests=$(kdelta get metrics/requests)
new_count=$((requests + 1))
kdelta set metrics/requests "$new_count"

# View counter history
kdelta log metrics/requests
```

### Session Storage

```bash
# Create session
kdelta set sessions/xyz123 '{
  "user_id": "alice",
  "created_at": "2025-11-24T17:00:00Z",
  "expires_at": "2025-11-24T18:00:00Z"
}'

# Read session
kdelta get sessions/xyz123

# List all sessions
kdelta list sessions
```

## Version Information

```bash
kdelta --version
```

## Help

```bash
# General help
kdelta --help

# Command-specific help
kdelta set --help
kdelta get --help
kdelta log --help
```

## See Also

- [README.md]README.md - Project overview and quick start
- [ARCHITECTURE.md]ARCHITECTURE.md - Technical architecture details
- [CONTRIBUTING.md]CONTRIBUTING.md - Contribution guidelines