stout 0.2.1

A fast, Rust-based Homebrew-compatible package manager
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
# stout Specification

A fast, Rust-based Homebrew-compatible package manager client.

## Overview

stout is a metadata-only package manager that provides a high-performance alternative to the Homebrew CLI. It consumes pre-computed package metadata from a GitHub repository and uses Homebrew's existing bottle infrastructure for actual package artifacts.

**Core Principles:**
- SQLite as the local index for fast queries
- Compressed JSON for full package metadata
- Metadata-only: no artifact hosting, point to upstream bottles
- Modular architecture for maintainability
- Full compatibility with existing Homebrew installations

---

## Why stout is Faster

### Current brew Bottlenecks

| Operation | What brew does | Time |
|-----------|----------------|------|
| **Any command** | Start Ruby interpreter | ~300-500ms |
| **`brew update`** | `git fetch` on homebrew-core (~700MB repo) | 10-60s |
| **`brew search`** | Load all formulas into Ruby, regex match | 2-5s |
| **`brew info`** | Load formula, evaluate Ruby DSL | 1-2s |
| **`brew install`** | Resolve deps in Ruby, sequential downloads | varies |

The fundamental issue: **brew evaluates Ruby on every command**.

```
$ time brew --version
Homebrew 4.2.0
real    0m0.502s   ← 500ms just to print version
```

### How stout Eliminates These

| Operation | What stout does | Time |
|-----------|-----------------|------|
| **Any command** | Start Rust binary | ~5ms |
| **`stout update`** | Download index.db.zst (~1-2MB) | 1-3s |
| **`stout search`** | SQLite FTS5 query | <50ms |
| **`stout info`** | SQLite lookup + fetch 500-byte JSON | <100ms |
| **`stout install`** | Parallel bottle downloads | faster |

### Speedup Sources

```
┌─────────────────────────────────────────────────────────────────┐
│                     BREW (current)                              │
│                                                                 │
│  User ──▶ Ruby ──▶ Load Formulas ──▶ Evaluate DSL ──▶ Result   │
│           500ms      varies            varies                   │
│                                                                 │
│  brew update: git fetch homebrew-core (700MB repo)              │
│  brew search: load ~7000 .rb files, regex each                  │
│  brew install: sequential dep resolution in Ruby                │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│                     STOUT (proposed)                            │
│                                                                 │
│  User ──▶ Rust ──▶ SQLite Query ──▶ Result                     │
│           5ms        <50ms                                      │
│                                                                 │
│  stout update: download index.db.zst (1-2MB)                    │
│  stout search: SELECT with FTS5 (instant)                       │
│  stout install: parallel async downloads, cached metadata       │
└─────────────────────────────────────────────────────────────────┘
```

### Detailed Breakdown

**1. No Ruby Interpreter**
- brew: Ruby VM startup on every command (~500ms)
- stout: Native Rust binary (~5ms startup)
- **Savings: ~500ms per command**

**2. No Git Operations**
- brew: `git fetch` on 700MB+ homebrew-core repo
- stout: HTTP GET for 1-2MB index file
- **Savings: 10-60s on update**

**3. Pre-computed Metadata**
- brew: Parses Ruby DSL at runtime to get version, deps, etc.
- stout: Already computed, stored as JSON, indexed in SQLite
- **Savings: eliminates Ruby evaluation entirely**

**4. SQLite vs In-Memory Ruby**
- brew: Loads formulas into Ruby objects for search
- stout: FTS5 full-text search on indexed database
- **Savings: 2-5s → <50ms for search**

**5. Parallel Downloads**
- brew: Often sequential operations
- stout: Tokio async runtime, concurrent bottle fetches
- **Savings: N bottles in parallel vs sequential**

**6. Local Caching with Invalidation**
- brew: Re-evaluates formulas each time
- stout: Caches formula JSON, only re-fetches if `json_hash` changed
- **Savings: skip network for unchanged formulas**

### Expected Performance

| Command | brew | stout | Speedup |
|---------|------|-------|---------|
| `--version` | 500ms | 5ms | **100x** |
| `search <query>` | 2-5s | <50ms | **40-100x** |
| `info <pkg>` | 1-2s | <100ms | **10-20x** |
| `update` | 10-60s | 1-3s | **10-20x** |
| `install` (cached) | varies | <10s | **2-5x** |

### What Stays the Same

stout uses the **exact same bottles** as brew:
- Same download URLs (ghcr.io/homebrew/core/...)
- Same checksums
- Same Cellar layout
- Same symlinks

The speedup comes from **how we get there**, not **what we install**.

---

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                        Data Pipeline                            │
│                                                                 │
│  ┌──────────┐     ┌──────────────┐     ┌───────────────────┐   │
│  │ Homebrew │────▶│  Transform   │────▶│  GitHub Release   │   │
│  │   API    │     │   Scripts    │     │  (index.db.zst)   │   │
│  └──────────┘     └──────────────┘     └───────────────────┘   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│                        Rust CLI                                 │
│                                                                 │
│  ┌──────────┐     ┌──────────┐     ┌──────────┐     ┌────────┐ │
│  │  index   │────▶│ resolve  │────▶│  fetch   │────▶│install │ │
│  └──────────┘     └──────────┘     └──────────┘     └────────┘ │
│       │                                                   │     │
│       ▼                                                   ▼     │
│  ~/.stout/                                    /opt/homebrew/    │
│  index.db                                     Cellar/           │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

---

## Data Pipeline

### Source: Homebrew API

Homebrew provides formula metadata via their JSON API:
- `https://formulae.brew.sh/api/formula.json` - All formulas
- `https://formulae.brew.sh/api/cask.json` - All casks

### Transform Scripts

Python scripts that:
1. Fetch latest formula/cask data from Homebrew API
2. Normalize and validate the data
3. Build SQLite index with compressed JSON blobs
4. Push to GitHub repository as a release artifact

#### Script: `scripts/sync.py`

```
Usage: python scripts/sync.py [--full | --incremental]

Options:
  --full         Rebuild entire index from scratch
  --incremental  Only update changed formulas (default)
  --dry-run      Build locally without pushing
  --output DIR   Output directory (default: ./dist)
```

#### Output Artifacts

```
dist/
├── index.db.zst          # Lightweight SQLite index (no blobs)
├── manifest.json         # Version, timestamp, checksums, changed files
└── formulas/
    ├── wget.json.zst
    ├── openssl@3.json.zst
    └── ...               # ~7000 individual formula files
```

#### GitHub Repository Structure

Repository: `github.com/<org>/stout-index`

```
stout-index/
├── index.db.zst          # ~1-2MB (queryable metadata only)
├── manifest.json         # Version info + list of changed formulas
├── formulas/
│   ├── a/
│   │   ├── aom.json.zst
│   │   ├── apr.json.zst
│   │   └── ...
│   ├── b/
│   │   ├── bash.json.zst
│   │   └── ...
│   └── z/
│       └── zstd.json.zst
└── casks/                # Phase 2
    └── ...
```

Files served via GitHub raw URLs or GitHub Pages:
- `https://raw.githubusercontent.com/<org>/stout-index/main/index.db.zst`
- `https://raw.githubusercontent.com/<org>/stout-index/main/formulas/w/wget.json.zst`

#### Automation

GitHub Actions workflows:

| Workflow | Trigger | Frequency | Updates |
|----------|---------|-----------|---------|
| `index-sync.yml` | Scheduled | Every 30 min | Index only |
| `formula-sync.yml` | Homebrew webhook / scheduled | Every 2h | Changed formulas |
| `full-rebuild.yml` | Manual / weekly | Weekly | Everything |

**Why split index and formulas:**
- Index is tiny (~1-2MB) → update very frequently
- Individual formulas fetched on-demand (install, info)
- Git tracks per-formula changes
- CDN caches individual files efficiently

---

## SQLite Index Schema

The index is **lightweight** - it contains only queryable metadata, not full formula data.
Full formula JSON is stored as individual files and fetched on-demand.

### Core Tables

```sql
-- Formula metadata (fast queries, search, listing)
CREATE TABLE formulas (
    name TEXT PRIMARY KEY,
    version TEXT NOT NULL,
    revision INTEGER DEFAULT 0,
    desc TEXT,
    homepage TEXT,
    license TEXT,
    tap TEXT DEFAULT 'homebrew/core',
    deprecated INTEGER DEFAULT 0,
    disabled INTEGER DEFAULT 0,
    has_bottle INTEGER DEFAULT 1,  -- Quick filter for bottle availability
    json_hash TEXT,                -- SHA256 of formula JSON (for cache invalidation)
    updated_at INTEGER             -- Unix timestamp
);

-- Full-text search
CREATE VIRTUAL TABLE formulas_fts USING fts5(
    name, desc,
    content='formulas',
    content_rowid='rowid'
);

-- Dependencies (for quick dependency queries without fetching JSON)
CREATE TABLE dependencies (
    formula TEXT NOT NULL,
    dep_name TEXT NOT NULL,
    dep_type TEXT NOT NULL,  -- 'runtime', 'build', 'test', 'optional'
    PRIMARY KEY (formula, dep_name, dep_type),
    FOREIGN KEY (formula) REFERENCES formulas(name)
);

-- Bottle availability matrix (quick platform compatibility check)
CREATE TABLE bottles (
    formula TEXT NOT NULL,
    platform TEXT NOT NULL,  -- 'arm64_sonoma', 'x86_64_linux', etc.
    PRIMARY KEY (formula, platform),
    FOREIGN KEY (formula) REFERENCES formulas(name)
);
-- Note: Full bottle URLs/checksums are in the individual JSON files

-- Aliases and old names (for search)
CREATE TABLE aliases (
    alias TEXT PRIMARY KEY,
    formula TEXT NOT NULL,
    FOREIGN KEY (formula) REFERENCES formulas(name)
);

-- Index metadata
CREATE TABLE meta (
    key TEXT PRIMARY KEY,
    value TEXT
);
-- Keys: 'version', 'created_at', 'homebrew_commit', 'formula_count'
```

### What's NOT in the index

The following data lives in individual `formulas/<name>.json.zst` files:
- Full bottle URLs and checksums
- Build instructions
- Caveats text
- Conflicts list
- Full dependency specs (with version constraints)
- Service definitions
- Pour bottle conditions

### Casks (Optional, Phase 2)

```sql
CREATE TABLE casks (
    token TEXT PRIMARY KEY,
    version TEXT NOT NULL,
    name TEXT,              -- Display name
    desc TEXT,
    homepage TEXT,
    url TEXT NOT NULL,
    sha256 TEXT,
    tap TEXT DEFAULT 'homebrew/cask',
    updated_at INTEGER
);

CREATE TABLE cask_json (
    token TEXT PRIMARY KEY,
    data BLOB NOT NULL,
    FOREIGN KEY (token) REFERENCES casks(token)
);
```

---

## Formula Translation

### Source: Homebrew API

We do **not** parse Ruby formulas directly. Homebrew provides a pre-computed JSON API:

```
https://formulae.brew.sh/api/formula.json      # All formulas (~15MB)
https://formulae.brew.sh/api/formula/<name>.json   # Single formula
https://formulae.brew.sh/api/cask.json         # All casks
```

This API is generated by Homebrew's CI when formulas change - Ruby evaluation happens on their side.

### Homebrew API Response (Input)

Example: `https://formulae.brew.sh/api/formula/wget.json`

```json
{
  "name": "wget",
  "full_name": "wget",
  "tap": "homebrew/core",
  "oldname": null,
  "oldnames": [],
  "aliases": [],
  "versioned_formulae": [],
  "desc": "Internet file retriever",
  "license": "GPL-3.0-or-later",
  "homepage": "https://www.gnu.org/software/wget/",
  "versions": {
    "stable": "1.24.5",
    "head": "HEAD",
    "bottle": true
  },
  "urls": {
    "stable": {
      "url": "https://ftp.gnu.org/gnu/wget/wget-1.24.5.tar.gz",
      "tag": null,
      "revision": null,
      "using": null,
      "checksum": "fa2dc35bab5184ecbc46a9ef83def2aaaa3f4c9f3c97d4bd19dcb07d4da637de"
    }
  },
  "revision": 0,
  "version_scheme": 0,
  "bottle": {
    "stable": {
      "rebuild": 0,
      "root_url": "https://ghcr.io/v2/homebrew/core",
      "files": {
        "arm64_sonoma": {
          "cellar": "/opt/homebrew/Cellar",
          "url": "https://ghcr.io/v2/homebrew/core/wget/blobs/sha256:...",
          "sha256": "..."
        },
        "arm64_ventura": { ... },
        "x86_64_linux": { ... }
      }
    }
  },
  "keg_only": false,
  "keg_only_reason": null,
  "options": [],
  "build_dependencies": ["pkg-config"],
  "dependencies": ["libidn2", "openssl@3"],
  "test_dependencies": [],
  "recommended_dependencies": [],
  "optional_dependencies": [],
  "uses_from_macos": [],
  "uses_from_macos_bounds": [],
  "requirements": [],
  "conflicts_with": [],
  "conflicts_with_reasons": [],
  "link_overwrite": [],
  "caveats": null,
  "installed": [],
  "linked_keg": null,
  "pinned": false,
  "outdated": false,
  "deprecated": false,
  "deprecation_date": null,
  "deprecation_reason": null,
  "disabled": false,
  "disable_date": null,
  "disable_reason": null,
  "post_install_defined": false,
  "service": null,
  "tap_git_head": "abc123...",
  "ruby_source_path": "Formula/w/wget.rb",
  "ruby_source_checksum": { "sha256": "..." }
}
```

### Translation Process

```
Homebrew API JSON
┌─────────────────────────────────────────────┐
│           Transform Script                  │
│                                             │
│  1. Fetch formula.json (all formulas)       │
│  2. For each formula:                       │
│     a. Extract index fields → SQLite        │
│     b. Normalize full data → stout JSON     │
│     c. Compress with zstd                   │
│  3. Build SQLite index                      │
│  4. Write individual .json.zst files        │
└─────────────────────────────────────────────┘
┌──────────────┐    ┌──────────────────────┐
│  index.db    │    │  formulas/<n>.json.zst│
│  (SQLite)    │    │  (individual files)   │
└──────────────┘    └──────────────────────┘
```

### Field Mapping

| Homebrew API Field | Index (SQLite) | Formula JSON |
|--------------------|----------------|--------------|
| `name` |`formulas.name` ||
| `versions.stable` |`formulas.version` ||
| `revision` |`formulas.revision` ||
| `desc` |`formulas.desc` ||
| `homepage` |`formulas.homepage` ||
| `license` |`formulas.license` ||
| `tap` |`formulas.tap` ||
| `deprecated` |`formulas.deprecated` ||
| `disabled` |`formulas.disabled` ||
| `bottle.stable.files` |`bottles` (platforms only) | ✓ (full URLs) |
| `dependencies` |`dependencies` ||
| `build_dependencies` |`dependencies` ||
| `optional_dependencies` |`dependencies` ||
| `aliases` |`aliases` ||
| `urls.stable` |||
| `caveats` |||
| `conflicts_with` |||
| `keg_only` |||
| `service` |||
| `post_install_defined` |||

### stout JSON Schema (Output)

Normalized, flattened structure optimized for the CLI:

```json
{
  "name": "wget",
  "version": "1.24.5",
  "revision": 0,
  "desc": "Internet file retriever",
  "homepage": "https://www.gnu.org/software/wget/",
  "license": "GPL-3.0-or-later",
  "tap": "homebrew/core",

  "urls": {
    "stable": {
      "url": "https://ftp.gnu.org/gnu/wget/wget-1.24.5.tar.gz",
      "sha256": "fa2dc35bab5184ecbc46a9ef83def2aaaa3f4c9f3c97d4bd19dcb07d4da637de"
    },
    "head": "https://git.savannah.gnu.org/git/wget.git"
  },

  "bottles": {
    "arm64_sonoma": {
      "url": "https://ghcr.io/v2/homebrew/core/wget/blobs/sha256:...",
      "sha256": "...",
      "cellar": "/opt/homebrew/Cellar"
    },
    "arm64_ventura": { ... },
    "x86_64_linux": { ... }
  },

  "dependencies": {
    "runtime": ["libidn2", "openssl@3"],
    "build": ["pkg-config"],
    "test": [],
    "optional": [],
    "recommended": []
  },

  "aliases": [],
  "conflicts_with": [],
  "caveats": null,

  "flags": {
    "keg_only": false,
    "deprecated": false,
    "disabled": false,
    "has_post_install": false
  },

  "service": null,

  "meta": {
    "ruby_source_path": "Formula/w/wget.rb",
    "tap_git_head": "abc123..."
  }
}
```

### Sync Script Pseudocode

```python
def sync():
    # 1. Fetch all formulas from Homebrew API
    formulas = fetch_json("https://formulae.brew.sh/api/formula.json")

    # 2. Initialize SQLite database
    db = create_database("index.db")

    for formula in formulas:
        # 3. Extract fields for index (fast queries)
        db.insert_formula(
            name=formula["name"],
            version=formula["versions"]["stable"],
            revision=formula["revision"],
            desc=formula["desc"],
            homepage=formula["homepage"],
            license=formula["license"],
            tap=formula["tap"],
            deprecated=formula["deprecated"],
            disabled=formula["disabled"],
            has_bottle=bool(formula.get("bottle")),
        )

        # 4. Insert dependencies
        for dep in formula.get("dependencies", []):
            db.insert_dependency(formula["name"], dep, "runtime")
        for dep in formula.get("build_dependencies", []):
            db.insert_dependency(formula["name"], dep, "build")
        # ... etc

        # 5. Insert bottle platforms
        if bottles := formula.get("bottle", {}).get("stable", {}).get("files"):
            for platform in bottles.keys():
                db.insert_bottle(formula["name"], platform)

        # 6. Transform to stout JSON format
        stout_json = transform_formula(formula)

        # 7. Compress and write individual file
        compressed = zstd.compress(json.dumps(stout_json))
        write_file(f"formulas/{formula['name'][0]}/{formula['name']}.json.zst", compressed)

        # 8. Store hash in index for cache invalidation
        json_hash = sha256(compressed)
        db.update_formula_hash(formula["name"], json_hash)

    # 9. Build FTS index
    db.rebuild_fts()

    # 10. Write manifest
    write_manifest(db.formula_count(), db.version())
```

### Compression Details

- **Algorithm**: zstd (level 19 for max compression)
- **Typical ratio**: 5-10x compression
- **Per-formula**: ~200-500 bytes compressed (from 2-5KB JSON)
- **Total formulas dir**: ~3-5MB for all ~7000 formulas

---

## Rust CLI

### Crate Structure

```
stout/
├── Cargo.toml
├── crates/
│   ├── stout-index/       # SQLite index management
│   │   ├── src/
│   │   │   ├── lib.rs
│   │   │   ├── db.rs      # Database operations
│   │   │   ├── schema.rs  # Table definitions
│   │   │   ├── sync.rs    # Index download/update
│   │   │   └── query.rs   # Search, lookup
│   │   └── Cargo.toml
│   │
│   ├── stout-resolve/     # Dependency resolution
│   │   ├── src/
│   │   │   ├── lib.rs
│   │   │   ├── graph.rs   # Dependency graph
│   │   │   ├── solver.rs  # SAT/pubgrub solver
│   │   │   └── plan.rs    # Installation plan
│   │   └── Cargo.toml
│   │
│   ├── stout-fetch/       # Download management
│   │   ├── src/
│   │   │   ├── lib.rs
│   │   │   ├── client.rs  # HTTP client (reqwest)
│   │   │   ├── progress.rs
│   │   │   ├── verify.rs  # Checksum verification
│   │   │   └── cache.rs   # Download cache
│   │   └── Cargo.toml
│   │
│   ├── stout-install/     # Package installation
│   │   ├── src/
│   │   │   ├── lib.rs
│   │   │   ├── extract.rs # Tar/bottle extraction
│   │   │   ├── link.rs    # Symlink to bin/
│   │   │   ├── receipt.rs # INSTALL_RECEIPT.json
│   │   │   └── hooks.rs   # Post-install scripts
│   │   └── Cargo.toml
│   │
│   └── stout-state/       # Local state management
│       ├── src/
│       │   ├── lib.rs
│       │   ├── config.rs  # User configuration
│       │   ├── installed.rs # Installed packages DB
│       │   └── lock.rs    # Lockfile support
│       └── Cargo.toml
│
└── src/
    ├── main.rs
    └── cli/
        ├── mod.rs
        ├── install.rs
        ├── uninstall.rs
        ├── search.rs
        ├── info.rs
        ├── update.rs
        ├── list.rs
        └── upgrade.rs
```

### Key Dependencies

```toml
[dependencies]
clap = { version = "4", features = ["derive"] }
rusqlite = { version = "0.31", features = ["bundled"] }
zstd = "0.13"
reqwest = { version = "0.12", features = ["stream", "rustls-tls"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
indicatif = "0.17"          # Progress bars
sha2 = "0.10"               # Checksum verification
tar = "0.4"
flate2 = "1"                # gzip for bottles
dirs = "5"                  # XDG paths
```

### CLI Commands

```
stout <command> [options]

Commands:
  install <formula>...    Install packages
  uninstall <formula>...  Remove packages
  upgrade [formula]...    Upgrade packages (all if none specified)
  search <query>          Search formulas
  info <formula>          Show package details
  list                    List installed packages
  update                  Update formula index
  doctor                  Check system health
  config                  Manage configuration

Options:
  -v, --verbose           Verbose output
  -q, --quiet             Suppress output
  --dry-run               Show what would be done
  --offline               Use cached index only
```

### CLI UX Design

Inspired by `uv` - fast, beautiful, informative.

#### Color Palette

```
Primary:    Cyan    (#06b6d4)  - Actions, commands
Success:    Green   (#22c55e)  - Completed, installed
Warning:    Yellow  (#eab308)  - Warnings, deprecations
Error:      Red     (#ef4444)  - Errors, failures
Muted:      Gray    (#6b7280)  - Secondary info, paths
Accent:     Blue    (#3b82f6)  - Links, versions
```

#### Output Examples

**Install:**
```
$ stout install wget ripgrep fd

Resolving dependencies...
  ✓ wget 1.24.5
  ✓ ripgrep 14.1.0
  ✓ fd 9.0.0
  + openssl@3 3.2.1 (dependency)
  + pcre2 10.42 (dependency)

Downloading 5 packages...
  ████████████████████████████████████████ 5/5 (12.4 MB)

Installing...
  ✓ openssl@3 3.2.1
  ✓ pcre2 10.42
  ✓ wget 1.24.5
  ✓ ripgrep 14.1.0
  ✓ fd 9.0.0

Installed 5 packages in 3.2s
```

**Search:**
```
$ stout search json

Found 47 formulas:

  jq 1.7.1                Command-line JSON processor
  fx 31.0.0               Terminal JSON viewer
  gojq 0.12.14            Pure Go implementation of jq
  jless 0.9.0             Command-line JSON viewer
  jsonlint 1.6.3          JSON parser and validator
  ...

Use 'stout info <formula>' for details
```

**Update:**
```
$ stout update

Fetching index...
  ████████████████████████████████████████ 1.8 MB

Updated to 2024.01.15.042 (7,012 formulas)
  + 3 new: foo, bar, baz
  ↑ 12 updated

Last sync: 2 minutes ago
```

**Info:**
```
$ stout info wget

wget 1.24.5
Internet file retriever

Homepage:  https://www.gnu.org/software/wget/
License:   GPL-3.0-or-later
Tap:       homebrew/core

Dependencies:
  ├── openssl@3 (runtime)
  ├── libidn2 (runtime)
  └── pkg-config (build)

Bottles:
  ✓ arm64_sonoma    ✓ arm64_ventura    ✓ x86_64_linux
  ✓ sonoma          ✓ ventura

Installed: No
```

**Upgrade:**
```
$ stout upgrade

Checking for updates...

2 packages can be upgraded:

  Package     Current    Latest
  ─────────────────────────────
  wget        1.24.4  →  1.24.5
  openssl@3   3.2.0   →  3.2.1

Upgrade all? [Y/n] y

Downloading...
  ████████████████████████████████████████ 2/2 (8.1 MB)

Installing...
  ✓ openssl@3 3.2.0 → 3.2.1
  ✓ wget 1.24.4 → 1.24.5

Upgraded 2 packages in 2.1s
```

**List:**
```
$ stout list

Installed packages (23):

  Name          Version     Size      Installed
  ────────────────────────────────────────────────
  wget          1.24.5      4.2 MB    2 days ago
  ripgrep       14.1.0      6.1 MB    1 week ago
  fd            9.0.0       3.8 MB    1 week ago
  jq            1.7.1       1.2 MB    2 weeks ago
  ...

Total: 23 packages, 142 MB
```

**Errors:**
```
$ stout install nonexistent

error: formula 'nonexistent' not found

Did you mean?
  • node
  • neotest
  • nextest

Run 'stout search <query>' to find packages
```

#### Progress Indicators

```rust
// Use indicatif with custom styles
use indicatif::{ProgressBar, ProgressStyle};

// Download progress
let style = ProgressStyle::default_bar()
    .template("{spinner:.cyan} {msg}\n  {bar:40.cyan/dim} {pos}/{len} ({bytes})")
    .progress_chars("━━╸━");

// Spinner for resolving
let style = ProgressStyle::default_spinner()
    .template("{spinner:.cyan} {msg}")
    .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏");
```

#### Design Principles

1. **Instant feedback** - Show spinner immediately, never hang silently
2. **Progressive disclosure** - Summary by default, `--verbose` for details
3. **Scannable output** - Aligned columns, clear hierarchy
4. **Color with purpose** - Green=success, red=error, cyan=action
5. **Helpful errors** - Suggest fixes, show similar matches
6. **Timing info** - Show how fast we are ("in 3.2s")
7. **No clutter** - No unnecessary blank lines or decorations

#### Key Dependencies for UX

```toml
indicatif = "0.17"      # Progress bars and spinners
console = "0.15"        # Terminal colors and styling
dialoguer = "0.11"      # Interactive prompts (Y/n)
unicode-width = "0.1"   # Proper column alignment
humansize = "2"         # "4.2 MB" formatting
humantime = "2"         # "2 days ago" formatting
```

---

## Local State

### Directory Structure

```
~/.stout/
├── config.toml           # User configuration
├── index.db              # SQLite index (decompressed, ~2-5MB)
├── manifest.json         # Current index version info
├── cache/
│   ├── formulas/         # Cached formula JSONs (decompressed)
│   │   ├── wget.json
│   │   ├── openssl@3.json
│   │   └── ...
│   └── downloads/        # Downloaded bottles (cleared periodically)
└── state/
    └── installed.toml    # Local installation tracking
```

### config.toml

```toml
[index]
# Base URL for stout-index repository (raw GitHub content)
base_url = "https://raw.githubusercontent.com/<org>/stout-index/main"
auto_update = true
update_interval = 1800  # seconds (30 min for index)

[install]
cellar = "/opt/homebrew/Cellar"
prefix = "/opt/homebrew"
parallel_downloads = 4

[cache]
max_size = "2GB"
formula_ttl = 86400     # 1 day - formula JSONs
download_ttl = 604800   # 7 days - bottle downloads
```

### installed.toml

```toml
# Tracks stout-managed installations
# Coexists with Homebrew's INSTALL_RECEIPT.json

[wget]
version = "1.24.5"
revision = 0
installed_at = 2024-01-15T10:30:00Z
installed_by = "stout"
requested = true  # Explicitly installed vs dependency

[openssl@3]
version = "3.2.1"
revision = 0
installed_at = 2024-01-15T10:29:55Z
installed_by = "stout"
requested = false  # Installed as dependency of wget
```

---

## Homebrew Compatibility

### Cellar Layout

stout uses the same Cellar structure as Homebrew:

```
/opt/homebrew/
├── Cellar/
│   └── wget/
│       └── 1.24.5/
│           ├── bin/
│           │   └── wget
│           ├── share/
│           ├── INSTALL_RECEIPT.json
│           └── .brew/
│               └── wget.rb  (optional, for `brew` compat)
├── bin/                     # Symlinks
│   └── wget -> ../Cellar/wget/1.24.5/bin/wget
└── opt/
    └── wget -> ../Cellar/wget/1.24.5
```

### INSTALL_RECEIPT.json

stout writes compatible receipts so `brew` can see stout-installed packages:

```json
{
  "homebrew_version": "4.x.x",
  "installed_as_dependency": false,
  "installed_on_request": true,
  "install_time": 1705312200,
  "source": {
    "tap": "homebrew/core"
  },
  "runtime_dependencies": [
    {"full_name": "openssl@3", "version": "3.2.1"}
  ]
}
```

### Side-by-Side Operation

- stout reads existing Homebrew installations
- `brew` can see stout-installed packages
- Users can mix `brew` and `stout` commands
- No conflicts: same paths, same receipts

---

## Sync Protocol

### Index Update (`stout update`)

```
1. GET manifest.json (ETag/If-Modified-Since for caching)
2. Compare manifest.index_version vs local version
3. If different:
   a. GET index.db.zst
   b. Verify sha256
   c. Decompress to ~/.stout/index.db
4. Note: Individual formula JSONs are NOT fetched here
```

### On-Demand Formula Fetch (`stout install/info`)

```
1. Check local cache: ~/.stout/cache/formulas/<name>.json
2. Compare cached json_hash vs index.formulas.json_hash
3. If missing or stale:
   a. GET formulas/<first-letter>/<name>.json.zst
   b. Decompress and cache locally
   c. Store json_hash for future validation
4. Use cached formula data
```

### Local Formula Cache

```
~/.stout/cache/formulas/
├── wget.json              # Decompressed, ready to use
├── openssl@3.json
└── ...
```

Cache invalidation via `json_hash` in index - no need to re-download if hash matches.

### Manifest Format

```json
{
  "version": "2024.01.15.042",
  "index_version": "2024.01.15.042",
  "index_sha256": "abc123...",
  "index_size": 1847293,
  "formula_count": 7012,
  "created_at": "2024-01-15T10:30:00Z",
  "homebrew_commit": "abc123def456"
}
```

### Offline Mode

When `--offline` or network unavailable:
- Use existing index.db
- Use cached formula JSONs
- Warn if index is stale (>24h)
- Fail gracefully if formula JSON not cached

---

## Security

### Checksums

- All downloads verified against sha256 in metadata
- Index itself verified against manifest checksum
- Failed verification = abort install

### Future Considerations

- Signed manifests (GPG or minisign)
- Content-addressable cache
- Pinned certificates for GitHub/GHCR

---

## Performance Targets

| Operation | Target |
|-----------|--------|
| `stout search <query>` | <50ms |
| `stout info <formula>` | <100ms |
| `stout update` (incremental) | <5s |
| `stout install` (cached bottle) | <10s |
| Index size (compressed) | <10MB |

---

## Phases

### Phase 1: Core CLI
- [ ] SQLite index crate
- [ ] Sync from GitHub releases
- [ ] search, info, list commands
- [ ] install (bottles only)
- [ ] uninstall, upgrade

### Phase 2: Full Feature Parity
- [ ] Cask support
- [ ] Build from source fallback
- [ ] Tap support (custom indexes)
- [ ] Lockfile support

### Phase 3: Enhancements
- [ ] Parallel installs
- [ ] Signed indexes
- [ ] Delta sync optimization
- [ ] Shell completions