@git-stunts/git-cas 5.3.2 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/ADVANCED_GUIDE.md +1027 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +449 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +926 -0
  6. package/README.md +106 -366
  7. package/SECURITY.md +993 -0
  8. package/SUPPORT.md +54 -0
  9. package/UPGRADING.md +299 -0
  10. package/bin/actions.js +70 -21
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +595 -449
  20. package/bin/passphrase-source.js +266 -0
  21. package/bin/restore-output-target.js +28 -0
  22. package/bin/ui/blocks/asset-card.js +109 -0
  23. package/bin/ui/blocks/health-dashboard.js +149 -0
  24. package/bin/ui/blocks/heatmap-block.js +67 -0
  25. package/bin/ui/blocks/merkle-explorer.js +163 -0
  26. package/bin/ui/blocks/operation-feed.js +176 -0
  27. package/bin/ui/blocks/wizard-block.js +168 -0
  28. package/bin/ui/components/short-sha.js +36 -0
  29. package/bin/ui/context.js +56 -1
  30. package/bin/ui/dashboard-cmds.js +1578 -13
  31. package/bin/ui/dashboard-view.js +612 -145
  32. package/bin/ui/dashboard.js +1255 -212
  33. package/bin/ui/encryption-card.js +69 -26
  34. package/bin/ui/heatmap.js +26 -54
  35. package/bin/ui/history-timeline.js +51 -19
  36. package/bin/ui/manifest-view.js +115 -60
  37. package/bin/ui/merkle-dag.js +83 -0
  38. package/bin/ui/progress.js +15 -9
  39. package/bin/ui/repo-treemap.js +328 -0
  40. package/bin/ui/shaders/bak-sneppen.js +180 -0
  41. package/bin/ui/shaders/fractal-zoom.js +99 -0
  42. package/bin/ui/shaders/merkle-tree.js +142 -0
  43. package/bin/ui/shaders/organic-flow.js +96 -0
  44. package/bin/ui/shaders/phase-portrait.js +93 -0
  45. package/bin/ui/store-wizard.js +367 -0
  46. package/bin/ui/theme.js +155 -0
  47. package/bin/ui/vault-report.js +495 -0
  48. package/build-info.json +4 -0
  49. package/docs/API.md +2254 -0
  50. package/docs/ENCRYPTION_MODES.md +33 -0
  51. package/docs/EXTENDING.md +174 -0
  52. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  53. package/docs/THREAT_MODEL.md +269 -0
  54. package/docs/VAULT_INTERNALS.md +251 -0
  55. package/docs/WALKTHROUGH.md +1868 -0
  56. package/docs/demo.gif +0 -0
  57. package/docs/releases/v6.0.0.md +104 -0
  58. package/examples/README.md +260 -0
  59. package/index.d.ts +273 -80
  60. package/index.js +220 -59
  61. package/package.json +35 -6
  62. package/scripts/migrate-encryption.js +680 -0
  63. package/src/domain/bytes/ByteLayout.js +96 -0
  64. package/src/domain/encoding/base64.js +91 -0
  65. package/src/domain/encoding/hex.js +14 -0
  66. package/src/domain/encoding/utf8.js +123 -0
  67. package/src/domain/encryption/schemes.js +132 -0
  68. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  69. package/src/domain/errors/CasError.d.ts +28 -0
  70. package/src/domain/errors/CasError.js +43 -6
  71. package/src/domain/errors/Codes.js +54 -0
  72. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  73. package/src/domain/errors/GitError.js +10 -0
  74. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  75. package/src/domain/errors/IntegrityError.js +10 -0
  76. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  77. package/src/domain/errors/InvalidOidError.js +10 -0
  78. package/src/domain/errors/InvalidOptionsError.js +10 -0
  79. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  80. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  81. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  82. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  83. package/src/domain/errors/PortNotImplementedError.js +10 -0
  84. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  85. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  86. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  87. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  88. package/src/domain/errors/createCasError.js +68 -0
  89. package/src/domain/errors/index.js +20 -0
  90. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  91. package/src/domain/helpers/codecBytes.js +34 -0
  92. package/src/domain/helpers/gitRefErrors.js +84 -0
  93. package/src/domain/helpers/scryptMaxmem.js +22 -0
  94. package/src/domain/outcomes/RestoreFailure.js +15 -0
  95. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  96. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  97. package/src/domain/outcomes/StoreFailure.js +15 -0
  98. package/src/domain/outcomes/StoreOutcome.js +11 -0
  99. package/src/domain/outcomes/StoreSuccess.js +17 -0
  100. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  101. package/src/domain/schemas/ManifestSchema.js +67 -13
  102. package/src/domain/services/CasService.d.ts +153 -53
  103. package/src/domain/services/CasService.js +322 -837
  104. package/src/domain/services/ChunkRepository.js +268 -0
  105. package/src/domain/services/CompressionStreams.js +72 -0
  106. package/src/domain/services/ConvergentEncryption.js +128 -0
  107. package/src/domain/services/GitTreeBuilder.js +86 -0
  108. package/src/domain/services/IntegrityVerifier.js +199 -0
  109. package/src/domain/services/KeyResolver.js +49 -42
  110. package/src/domain/services/ManifestDiff.js +56 -0
  111. package/src/domain/services/ManifestRepository.js +286 -0
  112. package/src/domain/services/PrefetchWindow.js +48 -0
  113. package/src/domain/services/RecipientService.js +157 -0
  114. package/src/domain/services/RedactingObservability.js +169 -0
  115. package/src/domain/services/RestorePipeline.js +68 -0
  116. package/src/domain/services/StorePipeline.js +201 -0
  117. package/src/domain/services/VaultKeyVerifier.js +101 -0
  118. package/src/domain/services/VaultMetadataCodec.js +206 -0
  119. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  120. package/src/domain/services/VaultPersistence.js +410 -0
  121. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  122. package/src/domain/services/VaultService.js +749 -251
  123. package/src/domain/services/VaultStateCache.js +225 -0
  124. package/src/domain/services/VaultTreeCodec.js +121 -0
  125. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  126. package/src/domain/strategies/Aad.js +39 -0
  127. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  128. package/src/domain/strategies/RestoreCompressed.js +40 -0
  129. package/src/domain/strategies/RestoreConvergent.js +44 -0
  130. package/src/domain/strategies/RestoreFramed.js +55 -0
  131. package/src/domain/strategies/RestorePlain.js +37 -0
  132. package/src/domain/strategies/RestoreStrategy.js +35 -0
  133. package/src/domain/strategies/RestoreWhole.js +135 -0
  134. package/src/domain/strategies/StoreConvergent.js +28 -0
  135. package/src/domain/strategies/StoreFramed.js +39 -0
  136. package/src/domain/strategies/StorePlain.js +20 -0
  137. package/src/domain/strategies/StoreStrategy.js +61 -0
  138. package/src/domain/strategies/StoreWhole.js +34 -0
  139. package/src/domain/value-objects/Chunk.js +1 -2
  140. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  141. package/src/domain/value-objects/Manifest.d.ts +40 -4
  142. package/src/domain/value-objects/Manifest.js +61 -20
  143. package/src/domain/value-objects/Oid.js +45 -0
  144. package/src/domain/value-objects/Slug.js +124 -0
  145. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  146. package/src/helpers/aesGcmMeta.js +55 -0
  147. package/src/helpers/canonicalBase64.js +1 -0
  148. package/src/helpers/kdfPolicy.js +194 -0
  149. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  150. package/src/infrastructure/adapters/FileIOHelper.js +180 -13
  151. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  152. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  153. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  154. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  155. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  156. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  157. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  158. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  159. package/src/infrastructure/chunkers/resolveChunker.js +10 -6
  160. package/src/infrastructure/codecs/CborCodec.js +3 -3
  161. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  162. package/src/infrastructure/createGitPlumbing.js +22 -0
  163. package/src/package-version.js +1 -0
  164. package/src/ports/ChunkingPort.js +3 -3
  165. package/src/ports/CodecPort.js +4 -4
  166. package/src/ports/CompressionPort.js +57 -0
  167. package/src/ports/CryptoPort.js +138 -50
  168. package/src/ports/GitPersistencePort.js +32 -2
  169. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  170. package/src/ports/GitRefPort.js +1 -1
  171. package/src/types/ambient.d.ts +10 -5
  172. package/test/CONVENTIONS.md +94 -0
  173. package/test/cycles/README.md +13 -0
package/GUIDE.md ADDED
@@ -0,0 +1,926 @@
1
+ # Developer Guide
2
+
3
+ Comprehensive guide to `@git-stunts/git-cas` -- content-addressed storage backed by Git's object database, with encryption, compression, chunking, and vault management.
4
+
5
+ For security posture and threat model, see [SECURITY.md](./SECURITY.md).
6
+ For architecture and port/adapter internals, see [ARCHITECTURE.md](./ARCHITECTURE.md).
7
+ For API reference, see [docs/API.md](./docs/API.md).
8
+ For extension points and custom adapter checklists, see [docs/EXTENDING.md](./docs/EXTENDING.md).
9
+ For store/restore state machines, see [docs/STORE_RESTORE_PIPELINE.md](./docs/STORE_RESTORE_PIPELINE.md).
10
+ For advanced topics (benchmarks, Merkle trees, large-asset strategies), see [ADVANCED_GUIDE.md](./ADVANCED_GUIDE.md).
11
+
12
+ ---
13
+
14
+ ## Choose Your Path
15
+
16
+ ### 1. Library Integration
17
+
18
+ Embed content-addressed storage into your JavaScript/TypeScript application.
19
+
20
+ - Start with [Library Quick Start](#library-quick-start) below.
21
+ - Understand the port/adapter model: [ARCHITECTURE.md](./ARCHITECTURE.md).
22
+ - Custom adapters: [docs/EXTENDING.md](./docs/EXTENDING.md).
23
+
24
+ ### 2. CLI / TUI Usage
25
+
26
+ Store, restore, and manage assets from the terminal.
27
+
28
+ - Jump to [CLI Reference](#cli-reference).
29
+ - Interactive explorer: `git-cas vault dashboard`.
30
+
31
+ ### 3. Agentic Automation
32
+
33
+ Machine-facing agent CLI for structured CI/CD or agentic workflows.
34
+
35
+ - [docs/API.md](./docs/API.md) for the agent command surface.
36
+ - Run: `git-cas agent <command>`.
37
+
38
+ ### 4. Contributing
39
+
40
+ - Read `WORKFLOW.md`, `docs/method/process.md`, and `BEARING.md` for project process.
41
+ - See [Architecture](#architecture) for orientation.
42
+
43
+ ---
44
+
45
+ ## Feature Coverage Map
46
+
47
+ This guide and [ADVANCED_GUIDE.md](./ADVANCED_GUIDE.md) are the complete
48
+ feature coverage pair. The quick path lives here; implementation mechanics,
49
+ limits, and port contracts live in the advanced guide.
50
+
51
+ | Feature Area | Covered Here | Advanced Coverage |
52
+ | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
53
+ | Facade lifecycle, JSON/CBOR factories, full constructor | [Library Quick Start](#library-quick-start), [Configuration Reference](#configuration-reference) | [Direct CasService and Custom Port Contracts](./ADVANCED_GUIDE.md#direct-casservice-and-custom-port-contracts) |
54
+ | Direct `CasService` construction | [Configuration Reference](#configuration-reference) notes the facade/direct split | [Direct CasService and Custom Port Contracts](./ADVANCED_GUIDE.md#direct-casservice-and-custom-port-contracts) |
55
+ | File, stream, tree, vault-safe store workflows | [Store Operations](#store-operations), [Vault Management](#vault-management) | [Store/Restore Pipeline](./docs/STORE_RESTORE_PIPELINE.md), [Manifest Integrity Hash](./ADVANCED_GUIDE.md#manifest-integrity-hash), [Merkle Manifests](./ADVANCED_GUIDE.md#merkle-manifests) |
56
+ | Restore modes and bounded memory behavior | [Restore Modes](#restore-modes) | [Store/Restore Pipeline](./docs/STORE_RESTORE_PIPELINE.md), [Parallel Chunk Restore](./ADVANCED_GUIDE.md#parallel-chunk-restore), [Streaming Decompression](./ADVANCED_GUIDE.md#streaming-decompression) |
57
+ | Fixed chunking, CDC, FastCDC normalization | [Chunking](#chunking) | [Content-Defined Chunking (CDC)](./ADVANCED_GUIDE.md#content-defined-chunking-cdc) |
58
+ | Encryption schemes and legacy migration | [Encryption](#encryption), [Migrating Legacy Encryption Schemes](#migrating-legacy-encryption-schemes) | [Encryption Schemes](./ADVANCED_GUIDE.md#encryption-schemes), [Convergent Encryption](./ADVANCED_GUIDE.md#convergent-encryption) |
59
+ | Passphrases, PBKDF2, scrypt, KDF policy | [Passphrase-Based Encryption](#passphrase-based-encryption) | [KDF Policy](./ADVANCED_GUIDE.md#kdf-policy) |
60
+ | Multi-recipient envelope encryption and key rotation | [Multi-Recipient (Envelope) Encryption](#multi-recipient-envelope-encryption), [Key and Recipient Management](#key-and-recipient-management) | [Envelope Encryption](./ADVANCED_GUIDE.md#envelope-encryption) |
61
+ | Vault init/list/resolve/remove, metadata, rotation, privacy mode | [Vault Management](#vault-management), [Vault Privacy Mode](#vault-privacy-mode) | [Vault Privacy Mode](./ADVANCED_GUIDE.md#vault-privacy-mode) |
62
+ | Compression and custom adapters | [Compression](#compression) | [CompressionPort Architecture](./ADVANCED_GUIDE.md#compressionport-architecture) |
63
+ | Manifest versions, format version, integrity hash, diffing | [Manifest Features](#manifest-features), [Manifest Diffing](#manifest-diffing) | [Format Version](./ADVANCED_GUIDE.md#format-version), [Manifest Integrity Hash](./ADVANCED_GUIDE.md#manifest-integrity-hash), [Manifest Diffing](./ADVANCED_GUIDE.md#manifest-diffing) |
64
+ | Inspection, verification, referenced chunk analysis, deprecated aliases | [Manifest Features](#manifest-features), [Inspection and Verification](#inspection-and-verification) | [Security Hardening Summary](./ADVANCED_GUIDE.md#security-hardening-summary) |
65
+ | Human CLI, TUI dashboard, agent CLI | [CLI Reference](#cli-reference) | [Operational Tooling](./ADVANCED_GUIDE.md#operational-tooling) |
66
+ | Runtime support, ports, custom adapters, resilience policy | [Architecture](#architecture) | [Direct CasService and Custom Port Contracts](./ADVANCED_GUIDE.md#direct-casservice-and-custom-port-contracts), [Configuration Reference](./ADVANCED_GUIDE.md#configuration-reference) |
67
+ | Release verification, migration, build stamping | [Migrating Legacy Encryption Schemes](#migrating-legacy-encryption-schemes) | [Operational Tooling](./ADVANCED_GUIDE.md#operational-tooling) |
68
+
69
+ ---
70
+
71
+ ## Library Quick Start
72
+
73
+ A complete init-store-tree-restore cycle:
74
+
75
+ ```js
76
+ import ContentAddressableStore from '@git-stunts/git-cas';
77
+
78
+ // 1. Initialize
79
+ const cas = await ContentAddressableStore.open({ cwd: '/path/to/repo' });
80
+
81
+ // 2. Store a file
82
+ const manifest = await cas.storeFile({
83
+ filePath: './photo.jpg',
84
+ slug: 'photos/vacation',
85
+ });
86
+
87
+ // 3. Create a Git tree (persists the manifest + chunks as a tree object)
88
+ const treeOid = await cas.createTree({ manifest });
89
+
90
+ // 4. Add to the vault index (GC-safe ref)
91
+ await cas.addToVault({ slug: 'photos/vacation', treeOid });
92
+
93
+ // 5. Restore later
94
+ const readBack = await cas.readManifest({ treeOid });
95
+ const { buffer } = await cas.restore({ manifest: readBack });
96
+ ```
97
+
98
+ ### Factory Methods
99
+
100
+ | Factory | Codec | Use Case |
101
+ | -------------------------------------------------- | ----- | ------------------------------------ |
102
+ | `await ContentAddressableStore.open({ cwd })` | JSON | Shortest normal application setup |
103
+ | `ContentAddressableStore.createJson({ plumbing })` | JSON | Human-readable manifests, debugging |
104
+ | `ContentAddressableStore.createCbor({ plumbing })` | CBOR | Compact binary manifests, production |
105
+
106
+ `open()` is async and accepts `cwd` plus the same facade options as the
107
+ constructor except `plumbing`. Use `createJson()` or `createCbor()` when you
108
+ already have a custom Git plumbing instance. Both explicit-plumbing factories
109
+ accept the same facade options as the constructor except `codec`, which is fixed
110
+ by the factory name.
111
+
112
+ ### Full Constructor
113
+
114
+ For complete control, use the constructor directly:
115
+
116
+ ```js
117
+ import ContentAddressableStore, {
118
+ CborCodec,
119
+ EventEmitterObserver,
120
+ CdcChunker,
121
+ NodeCompressionAdapter,
122
+ } from '@git-stunts/git-cas';
123
+
124
+ const cas = new ContentAddressableStore({
125
+ plumbing,
126
+ chunkSize: 128 * 1024, // 128 KiB chunks
127
+ codec: new CborCodec(),
128
+ observability: new EventEmitterObserver(),
129
+ merkleThreshold: 500, // Merkle sub-manifests above 500 chunks
130
+ concurrency: 4, // Parallel chunk I/O
131
+ maxRestoreBufferSize: 256 * 1024 * 1024, // 256 MiB buffer limit
132
+ compressionAdapter: new NodeCompressionAdapter(),
133
+ chunking: {
134
+ // CDC chunking
135
+ strategy: 'cdc',
136
+ targetChunkSize: 64 * 1024,
137
+ minChunkSize: 16 * 1024,
138
+ maxChunkSize: 256 * 1024,
139
+ },
140
+ });
141
+ ```
142
+
143
+ ---
144
+
145
+ ## Store Operations
146
+
147
+ ### `store({ source, slug, filename })`
148
+
149
+ Stores data from any async iterable:
150
+
151
+ ```js
152
+ async function* generateData() {
153
+ yield new TextEncoder().encode('chunk one');
154
+ yield new TextEncoder().encode('chunk two');
155
+ }
156
+
157
+ const manifest = await cas.store({
158
+ source: generateData(),
159
+ slug: 'data/stream-example',
160
+ filename: 'output.bin',
161
+ });
162
+ ```
163
+
164
+ ### `storeFile({ filePath, slug })`
165
+
166
+ Convenience method that reads a file from disk:
167
+
168
+ ```js
169
+ const manifest = await cas.storeFile({
170
+ filePath: '/absolute/path/to/archive.tar.gz',
171
+ slug: 'backups/2026-04-23',
172
+ });
173
+ ```
174
+
175
+ The filename defaults to the basename of `filePath`. Override it with the optional `filename` parameter.
176
+
177
+ Use `chunking` on a single store call when one asset needs a different strategy
178
+ from the facade default:
179
+
180
+ ```js
181
+ const manifest = await cas.storeFile({
182
+ filePath: './large-archive.tar',
183
+ slug: 'archives/large',
184
+ chunking: { strategy: 'cdc' },
185
+ });
186
+ ```
187
+
188
+ This override is scoped to that operation. The next `store()` or `storeFile()`
189
+ call returns to the facade's configured chunker unless it also supplies
190
+ `chunking`.
191
+
192
+ ---
193
+
194
+ ## Encryption
195
+
196
+ All store and restore methods accept encryption options. Encryption is AES-256-GCM.
197
+
198
+ ### Encryption Schemes
199
+
200
+ | Scheme | Description | Default When |
201
+ | ------------ | ----------------------------------------------------------------------------------------------- | ------------------------- |
202
+ | `convergent` | Per-chunk encryption keyed by content hash; preserves CDC deduplication across encrypted stores | CDC chunking + encryption |
203
+ | `framed` | Streaming framed encryption with per-frame AAD binding to slug | Non-CDC encrypted stores |
204
+ | `whole` | Whole-object encryption with AAD binding to slug | Explicit only |
205
+
206
+ AAD (Additional Authenticated Data) is always on for `whole` and `framed` schemes, binding ciphertext to the asset slug.
207
+
208
+ **Convergent encryption** is the default when CDC chunking is active and an encryption key is provided. It encrypts each chunk independently using a key derived from the chunk content, so identical plaintext chunks produce identical ciphertext -- preserving deduplication. For non-CDC stores, the default is `framed`.
209
+
210
+ #### Legacy Schemes
211
+
212
+ The v1/v2 scheme identifiers (`whole-v1`, `whole-v2`, `framed-v1`, `framed-v2`, `convergent-v1`) are no longer supported. Attempting to restore a manifest with a legacy scheme throws a `LEGACY_SCHEME` error. Run `scripts/migrate-encryption.js` to upgrade old manifests to current scheme names. See [Migration](#migrating-legacy-encryption-schemes) below.
213
+
214
+ ### Raw Key Encryption
215
+
216
+ ```js
217
+ import { randomBytes } from 'node:crypto';
218
+
219
+ const key = randomBytes(32); // 32-byte AES-256 key
220
+
221
+ // Store encrypted
222
+ const manifest = await cas.storeFile({
223
+ filePath: './secret.pdf',
224
+ slug: 'docs/secret',
225
+ encryptionKey: key,
226
+ });
227
+
228
+ // Restore encrypted
229
+ const treeOid = await cas.createTree({ manifest });
230
+ const readBack = await cas.readManifest({ treeOid });
231
+ const { buffer } = await cas.restore({
232
+ manifest: readBack,
233
+ encryptionKey: key,
234
+ });
235
+ ```
236
+
237
+ ### Passphrase-Based Encryption
238
+
239
+ Derives a key using PBKDF2 (default) or scrypt:
240
+
241
+ PBKDF2 works across Node, Bun, and Deno/Web Crypto. scrypt requires a Node/Bun
242
+ crypto adapter; Web Crypto runtimes report a capability error for scrypt.
243
+
244
+ ```js
245
+ // Store with passphrase (PBKDF2)
246
+ const pbkdf2Manifest = await cas.storeFile({
247
+ filePath: './secret.pdf',
248
+ slug: 'docs/secret',
249
+ passphrase: 'my-strong-passphrase',
250
+ });
251
+
252
+ // Store with scrypt
253
+ const scryptManifest = await cas.storeFile({
254
+ filePath: './secret.pdf',
255
+ slug: 'docs/secret',
256
+ passphrase: 'my-strong-passphrase',
257
+ kdfOptions: { algorithm: 'scrypt' },
258
+ });
259
+
260
+ // Restore with passphrase
261
+ const readBack = await cas.readManifest({ treeOid });
262
+ const { buffer } = await cas.restore({
263
+ manifest: readBack,
264
+ passphrase: 'my-strong-passphrase',
265
+ });
266
+ ```
267
+
268
+ ### Multi-Recipient (Envelope) Encryption
269
+
270
+ Envelope encryption wraps a random DEK with each recipient's KEK. Adding or removing recipients never re-encrypts the data.
271
+
272
+ ```js
273
+ import { randomBytes } from 'node:crypto';
274
+
275
+ const aliceKey = randomBytes(32);
276
+ const bobKey = randomBytes(32);
277
+
278
+ // Store with recipients
279
+ const manifest = await cas.storeFile({
280
+ filePath: './shared-doc.pdf',
281
+ slug: 'team/shared-doc',
282
+ recipients: [
283
+ { label: 'alice', key: aliceKey },
284
+ { label: 'bob', key: bobKey },
285
+ ],
286
+ });
287
+
288
+ // Restore using any recipient's key
289
+ const readBack = await cas.readManifest({ treeOid });
290
+ const { buffer } = await cas.restore({
291
+ manifest: readBack,
292
+ encryptionKey: aliceKey,
293
+ });
294
+
295
+ // Add a recipient
296
+ const updated = await cas.addRecipient({
297
+ manifest: readBack,
298
+ existingKey: aliceKey, // Any current recipient's key
299
+ newRecipientKey: carolKey,
300
+ label: 'carol',
301
+ });
302
+
303
+ // Remove a recipient
304
+ const shrunk = await cas.removeRecipient({
305
+ manifest: updated,
306
+ label: 'bob',
307
+ });
308
+
309
+ // List recipients
310
+ const labels = await cas.listRecipients(readBack);
311
+ // => ['alice', 'bob']
312
+
313
+ // Rotate a recipient's key (no data re-encryption)
314
+ const rotated = await cas.rotateKey({
315
+ manifest: readBack,
316
+ oldKey: aliceKey,
317
+ newKey: aliceNewKey,
318
+ label: 'alice', // Optional: target a specific recipient
319
+ });
320
+ ```
321
+
322
+ ### Explicit Scheme Selection
323
+
324
+ Override the default scheme:
325
+
326
+ ```js
327
+ // Force framed encryption (even with CDC chunking)
328
+ const framedManifest = await cas.storeFile({
329
+ filePath: './large-video.mp4',
330
+ slug: 'media/video',
331
+ encryptionKey: key,
332
+ encryption: {
333
+ scheme: 'framed', // 'whole', 'framed', or 'convergent'
334
+ frameBytes: 128 * 1024, // 128 KiB frames (framed scheme only)
335
+ },
336
+ });
337
+
338
+ // Force whole-object encryption
339
+ const wholeManifest = await cas.storeFile({
340
+ filePath: './small-config.json',
341
+ slug: 'config/app',
342
+ encryptionKey: key,
343
+ encryption: { scheme: 'whole' },
344
+ });
345
+ ```
346
+
347
+ ### Migrating Legacy Encryption Schemes
348
+
349
+ Manifests created with earlier versions may use v1/v2 scheme identifiers (`whole-v1`, `whole-v2`, `framed-v1`, `framed-v2`, `convergent-v1`). These are no longer supported in the main codebase. The migration script decrypts using the legacy logic and re-stores using current scheme names with AAD always on.
350
+
351
+ ```sh
352
+ node scripts/migrate-encryption.js
353
+ printf '%s\n' 'my-secret' | node scripts/migrate-encryption.js --execute --passphrase-file -
354
+ node scripts/migrate-encryption.js --execute --key-file ./asset.key
355
+ ```
356
+
357
+ The migration script handles both fast (rename-only for v2 schemes) and full (re-encryption with AAD for v1 schemes) migration paths. Full migration accepts `--passphrase-file`, `--key-file`, or inline `--passphrase` for compatibility; inline passphrases print a warning because they can leak through shell history and process listings. For privacy-enabled vaults, add `--vault-passphrase-file` or `--vault-key-file` when the vault passphrase differs from the content passphrase. The inline `--vault-passphrase` fallback is still accepted with the same warning. The main `src/` codebase throws `LEGACY_SCHEME` if it encounters a v1/v2 identifier.
358
+
359
+ ---
360
+
361
+ ## Chunking
362
+
363
+ Content is split into chunks before storage. Two strategies are available:
364
+
365
+ ### Fixed Chunking (Default)
366
+
367
+ Splits data into equal-sized chunks. Simple and predictable.
368
+
369
+ ```js
370
+ const cas = ContentAddressableStore.createJson({
371
+ plumbing,
372
+ chunkSize: 512 * 1024, // 512 KiB chunks
373
+ });
374
+ ```
375
+
376
+ ### Content-Defined Chunking (CDC)
377
+
378
+ Uses a rolling hash to find chunk boundaries based on content. Provides deduplication across similar files.
379
+
380
+ ```js
381
+ const cas = new ContentAddressableStore({
382
+ plumbing,
383
+ chunking: {
384
+ strategy: 'cdc',
385
+ targetChunkSize: 64 * 1024, // 64 KiB target
386
+ minChunkSize: 16 * 1024, // 16 KiB minimum
387
+ maxChunkSize: 256 * 1024, // 256 KiB maximum
388
+ },
389
+ });
390
+ ```
391
+
392
+ CDC parameters:
393
+
394
+ | Parameter | Description |
395
+ | ----------------- | ------------------------------------------------- |
396
+ | `targetChunkSize` | Average chunk size the rolling hash targets |
397
+ | `minChunkSize` | Minimum chunk size (never split smaller) |
398
+ | `maxChunkSize` | Maximum chunk size (force split at this boundary) |
399
+
400
+ > **Note**: CDC deduplication is ineffective with standard encryption (`whole` or `framed`), since ciphertext is pseudorandom. Use the `convergent` scheme (the default for CDC + encryption) to preserve deduplication.
401
+
402
+ ---
403
+
404
+ ## Compression
405
+
406
+ Enable gzip compression to reduce storage size. Compression runs before encryption (compress-then-encrypt). Plaintext and gzip-compressed content both stream during store and restore, so memory usage stays low regardless of file size.
407
+
408
+ ### Library
409
+
410
+ ```js
411
+ const manifest = await cas.storeFile({
412
+ filePath: './large-log.txt',
413
+ slug: 'logs/2026-04-23',
414
+ compression: { algorithm: 'gzip' },
415
+ });
416
+
417
+ // Decompression is automatic on restore -- the manifest records the algorithm.
418
+ const { buffer } = await cas.restore({ manifest: readBack });
419
+ ```
420
+
421
+ ### Custom Compression Adapter
422
+
423
+ Implement the `CompressionPort` interface to use a different algorithm:
424
+
425
+ ```js
426
+ import { CompressionPort } from '@git-stunts/git-cas';
427
+
428
+ class BrotliAdapter extends CompressionPort {
429
+ async compressBuffer(buffer) {
430
+ /* ... */
431
+ }
432
+ async decompressBuffer(buffer) {
433
+ /* ... */
434
+ }
435
+ async *compressStream(source) {
436
+ /* ... */
437
+ }
438
+ async *decompressStream(source) {
439
+ /* ... */
440
+ }
441
+ }
442
+
443
+ const cas = new ContentAddressableStore({
444
+ plumbing,
445
+ compressionAdapter: new BrotliAdapter(),
446
+ });
447
+ ```
448
+
449
+ ---
450
+
451
+ ## Manifest Diffing
452
+
453
+ Compare two manifests to find added, removed, and unchanged chunks. This is a pure function with no I/O -- useful for incremental backup, sync, and deduplication analysis.
454
+
455
+ ### Library
456
+
457
+ ```js
458
+ // Static method (requires class, not an instance)
459
+ import CasService from '@git-stunts/git-cas/service';
460
+ const serviceDiff = CasService.diffManifests(oldManifest, newManifest);
461
+
462
+ // Standalone function
463
+ import { diffManifests } from '@git-stunts/git-cas';
464
+ const standaloneDiff = diffManifests(oldManifest, newManifest);
465
+
466
+ console.log(standaloneDiff.summary);
467
+ // => {
468
+ // addedCount: 3, removedCount: 1, unchangedCount: 42,
469
+ // addedBytes: 196608, removedBytes: 65536, unchangedBytes: 2752512,
470
+ // }
471
+ console.log(standaloneDiff.added); // Chunk[] -- new chunks in newManifest
472
+ console.log(standaloneDiff.removed); // Chunk[] -- chunks only in oldManifest
473
+ console.log(standaloneDiff.unchanged); // Chunk[] -- chunks in both (by digest)
474
+ ```
475
+
476
+ ---
477
+
478
+ ## Vault Management
479
+
480
+ The vault is a GC-safe index backed by `refs/cas/vault`. It maps slugs to Git tree OIDs, ensuring stored assets are reachable by Git and not garbage-collected.
481
+
482
+ ### Initialize the Vault
483
+
484
+ ```js
485
+ // Plain vault (no encryption)
486
+ await cas.initVault();
487
+
488
+ // Encrypted vault with passphrase
489
+ await cas.initVault({
490
+ passphrase: 'vault-secret',
491
+ kdfOptions: { algorithm: 'pbkdf2' }, // or 'scrypt'
492
+ });
493
+
494
+ // Encrypted vault with privacy mode
495
+ await cas.initVault({
496
+ passphrase: 'vault-secret',
497
+ kdfOptions: { algorithm: 'pbkdf2' },
498
+ privacy: true,
499
+ });
500
+ ```
501
+
502
+ ### Add, List, Resolve, Remove
503
+
504
+ ```js
505
+ // Add an entry
506
+ await cas.addToVault({ slug: 'photos/vacation', treeOid });
507
+
508
+ // Overwrite an existing entry
509
+ await cas.addToVault({ slug: 'photos/vacation', treeOid: newTreeOid, force: true });
510
+
511
+ // List all entries
512
+ const entries = await cas.listVault();
513
+ // => [{ slug: 'photos/vacation', treeOid: 'abc123...' }, ...]
514
+
515
+ // Resolve a single slug to its tree OID
516
+ const oid = await cas.resolveVaultEntry({ slug: 'photos/vacation' });
517
+
518
+ // Remove an entry
519
+ const { commitOid, removedTreeOid } = await cas.removeFromVault({
520
+ slug: 'photos/vacation',
521
+ });
522
+ ```
523
+
524
+ ### Rotate Vault Passphrase
525
+
526
+ Re-wraps every envelope-encrypted entry's DEK with a new key derived from `newPassphrase`. Entries using direct-key encryption are skipped.
527
+
528
+ ```js
529
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase({
530
+ oldPassphrase: 'old-secret',
531
+ newPassphrase: 'new-secret',
532
+ kdfOptions: { algorithm: 'scrypt' }, // optional: change KDF algorithm
533
+ });
534
+ ```
535
+
536
+ ### Get Vault Metadata
537
+
538
+ ```js
539
+ const metadata = await cas.getVaultMetadata();
540
+ // => { version: 1, encryption: { cipher: 'aes-256-gcm', kdf: { ... }, verifier: { ... } } }
541
+ ```
542
+
543
+ Encrypted v6 vaults include a verifier in `.vault.json`, so tools can reject a
544
+ wrong passphrase even before the vault contains entries. Normal CLI and facade
545
+ flows verify derived vault keys automatically. Custom tools that derive vault
546
+ keys themselves should call `verifyVaultKey({ encryptionKey })` before using the
547
+ key.
548
+
549
+ ---
550
+
551
+ ## Vault Privacy Mode
552
+
553
+ When privacy mode is enabled, vault entry names are stored as HMAC hashes instead of plaintext slugs. This prevents an attacker who has access to the Git object database from learning what assets are stored, even without the encryption key.
554
+
555
+ ### Enabling Privacy Mode
556
+
557
+ Privacy mode requires vault-level encryption. Enable it at vault initialization:
558
+
559
+ ```js
560
+ await cas.initVault({
561
+ passphrase: 'vault-secret',
562
+ kdfOptions: { algorithm: 'pbkdf2' },
563
+ privacy: true,
564
+ });
565
+ ```
566
+
567
+ ### Limitations
568
+
569
+ - Privacy mode cannot be enabled on an existing vault -- it must be set at init time.
570
+ - All vault read operations that need to resolve slugs require the encryption key, since the slug-to-HMAC mapping is itself encrypted.
571
+ - Privacy mode adds overhead: an encrypted `.privacy-index` blob is maintained alongside the vault tree.
572
+
573
+ ---
574
+
575
+ ## Manifest Features
576
+
577
+ ### Manifest Versions and Format Version
578
+
579
+ Manifests are versioned value objects that describe a stored asset:
580
+
581
+ - **v1**: Flat chunk list with SHA-256 integrity hashes.
582
+ - **v2**: Merkle sub-manifest support for large files. Activated when chunk count exceeds `merkleThreshold` (default 1000).
583
+
584
+ Each manifest also carries an optional `formatVersion` field -- a semver string (e.g. `"6.0.0"`) stamped by the library version that created it. This enables forward-compatible tooling to detect which features a manifest may use.
585
+
586
+ ### Reading a Manifest
587
+
588
+ ```js
589
+ const manifest = await cas.readManifest({ treeOid });
590
+
591
+ console.log(manifest.slug); // 'photos/vacation'
592
+ console.log(manifest.filename); // 'photo.jpg'
593
+ console.log(manifest.size); // total bytes
594
+ console.log(manifest.chunks.length); // number of chunks
595
+ console.log(manifest.encryption); // encryption metadata or undefined
596
+ console.log(manifest.compression); // compression metadata or undefined
597
+ console.log(manifest.formatVersion); // '6.0.0' or undefined (older manifests)
598
+ ```
599
+
600
+ ### Inspecting an Asset
601
+
602
+ Returns metadata without performing a full restore:
603
+
604
+ ```js
605
+ const info = await cas.inspectAsset({ treeOid });
606
+ // => { slug: 'photos/vacation', chunksOrphaned: 4 }
607
+ ```
608
+
609
+ ### Integrity Verification
610
+
611
+ Verifies every chunk's SHA-256 hash against the manifest:
612
+
613
+ ```js
614
+ const ok = await cas.verifyIntegrity(manifest);
615
+ if (!ok) {
616
+ console.error('Integrity check failed -- data may be corrupted');
617
+ }
618
+ ```
619
+
620
+ ---
621
+
622
+ ## Restore Modes
623
+
624
+ Three restore modes serve different use cases. When `concurrency` is greater than 1, chunk reads are parallelized for faster restore.
625
+
626
+ ### `restore({ manifest })` -- Buffered to Memory
627
+
628
+ Returns the entire file as a single buffer. Best for small-to-medium files.
629
+
630
+ ```js
631
+ const manifest = await cas.readManifest({ treeOid });
632
+ const { buffer, bytesWritten } = await cas.restore({ manifest });
633
+ ```
634
+
635
+ Encrypted content requires a key:
636
+
637
+ ```js
638
+ const { buffer } = await cas.restore({
639
+ manifest,
640
+ encryptionKey: key,
641
+ // or: passphrase: 'secret',
642
+ });
643
+ ```
644
+
645
+ The `maxRestoreBufferSize` option (default 512 MiB) guards against out-of-memory errors.
646
+
647
+ ### `restoreFile({ manifest, outputPath, baseDirectory })` -- Atomic File Write
648
+
649
+ Writes directly to disk. Handles streaming internally for framed-encrypted and compressed content.
650
+
651
+ ```js
652
+ const manifest = await cas.readManifest({ treeOid });
653
+ const { bytesWritten } = await cas.restoreFile({
654
+ manifest,
655
+ outputPath: '/tmp/restored-photo.jpg',
656
+ baseDirectory: '/tmp',
657
+ encryptionKey: key, // if encrypted
658
+ });
659
+ ```
660
+
661
+ ### `restoreStream({ manifest })` -- Async Iterable
662
+
663
+ Returns an async iterable of `Uint8Array` chunks. Best for large files, piping to other streams, or memory-constrained environments.
664
+
665
+ ```js
666
+ const manifest = await cas.readManifest({ treeOid });
667
+
668
+ for await (const chunk of cas.restoreStream({ manifest, encryptionKey: key })) {
669
+ process.stdout.write(chunk);
670
+ }
671
+ ```
672
+
673
+ ### When to Use Each
674
+
675
+ | Mode | Memory | Streaming | Use Case |
676
+ | --------------- | ---------------- | -------------- | ---------------------------------- |
677
+ | `restore` | Full file in RAM | No | Small files, in-memory processing |
678
+ | `restoreFile` | Low | Yes (internal) | Disk targets, atomic writes |
679
+ | `restoreStream` | Low | Yes (external) | Pipes, HTTP responses, large files |
680
+
681
+ ---
682
+
683
+ ## Streaming Surface
684
+
685
+ | Surface | Streaming API? | Non-streaming API? | Notes |
686
+ | ------------------------------- | ------------------------------------------ | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
687
+ | Write | `store({ source, ... })`, `storeFile(...)` | No dedicated non-streaming store facade | Write ingress is stream-based. CDC + encryption defaults to `convergent` (per-chunk deterministic encryption preserving dedup). Fixed + encryption defaults to `framed`. |
688
+ | Read: plaintext | `restoreStream(...)`, `restoreFile(...)` | `restore(...)` | True chunk-by-chunk streaming restore. |
689
+ | Read: encrypted `whole` | `restoreStream(...)`, `restoreFile(...)` | `restore(...)` | `restoreStream()` is the buffered compatibility path. Uncompressed `restoreFile()` verifies chunks, streams tentative plaintext through whole-object AES-GCM decryption into a temp-file path, and renames into place only after auth succeeds. AAD (slug) is always bound. On Web Crypto runtimes this decrypt step is still one-shot internally, bounded by `maxDecryptionBufferSize`. |
690
+ | Read: encrypted `framed` | `restoreStream(...)`, `restoreFile(...)` | `restore(...)` | True authenticated streaming restore. Plaintext is yielded frame-by-frame after each frame is verified. Per-frame AAD is always bound. |
691
+ | Read: compressed-only | `restoreStream(...)`, `restoreFile(...)` | `restore(...)` | Plaintext + gzip now streams end-to-end. `restoreFile()` streams gunzip output through a bounded temp-file path. |
692
+ | Read: compressed + `whole` | `restoreStream(...)`, `restoreFile(...)` | `restore(...)` | Auth must complete before gunzip. `restoreFile()` therefore preserves the auth-before-decompress boundary and may buffer the encrypted compressed payload; use `framed` or `convergent` for large compressed encrypted assets. |
693
+ | Read: compressed + `framed` | `restoreStream(...)`, `restoreFile(...)` | `restore(...)` | Streaming decrypt, then streaming gunzip. |
694
+ | Read: encrypted `convergent` | `restoreStream(...)`, `restoreFile(...)` | `restore(...)` | True per-chunk streaming restore. Each chunk is decrypted individually using a key derived from its content hash. Parallel chunk restore via prefetch window when concurrency > 1. |
695
+ | Read: compressed + `convergent` | `restoreStream(...)`, `restoreFile(...)` | `restore(...)` | Per-chunk convergent decrypt, then streaming gunzip. |
696
+ | Verify | No streaming verify surface | `verifyIntegrity(manifest, options?)` | Verifies chunk digests for all content. `whole` auth-checks the full ciphertext; `framed` parses and auth-checks every frame; `convergent` decrypts each chunk and verifies plaintext digests. |
697
+
698
+ Runtime note: `framed` is the honest cross-runtime streaming answer. On Node and Bun, `whole restoreFile()` has the stronger low-memory path; on Web Crypto runtimes such as Deno, `whole` remains bounded-buffer rather than true streaming.
699
+
700
+ ---
701
+
702
+ ## CLI Reference
703
+
704
+ All commands support `--json` for machine-readable output and `--quiet` to suppress progress.
705
+
706
+ ### Store and Restore
707
+
708
+ | Command | Description |
709
+ | ----------------------------------------------- | ------------------------------ |
710
+ | `git-cas store <file> --slug <slug>` | Store a file into Git CAS |
711
+ | `git-cas restore --out <path> --slug <slug>` | Restore a file from vault slug |
712
+ | `git-cas restore --out <path> --oid <tree-oid>` | Restore a file from tree OID |
713
+
714
+ **Store flags:**
715
+
716
+ | Flag | Description |
717
+ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
718
+ | `--slug <slug>` | Asset slug identifier (required) |
719
+ | `--tree` | Create Git tree and add to vault |
720
+ | `--force` | Overwrite existing vault entry (requires `--tree`) |
721
+ | `--key-file <path>` | Path to 32-byte raw encryption key file |
722
+ | `--recipient <label:keyfile>` | Envelope recipient (repeatable) |
723
+ | `--vault-passphrase <pass>` | Inline vault passphrase (accepted with warning; prefer `--vault-passphrase-file -`, `GIT_CAS_PASSPHRASE`, or `--os-keychain-target`) |
724
+ | `--vault-passphrase-file <path>` | Read passphrase from file (`-` for stdin) |
725
+ | `--os-keychain-target <target>` | Read passphrase from OS keychain via `@git-stunts/vault` |
726
+ | `--os-keychain-account <account>` | Keychain account namespace (default: `git-cas`) |
727
+ | `--gzip` | Enable gzip compression |
728
+ | `--strategy <fixed\|cdc>` | Chunking strategy |
729
+ | `--chunk-size <n>` | Chunk size in bytes |
730
+ | `--target-chunk-size <n>` | CDC target chunk size |
731
+ | `--min-chunk-size <n>` | CDC minimum chunk size |
732
+ | `--max-chunk-size <n>` | CDC maximum chunk size |
733
+ | `--concurrency <n>` | Parallel chunk I/O operations |
734
+ | `--codec <json\|cbor>` | Manifest codec |
735
+ | `--merkle-threshold <n>` | Chunk count for Merkle sub-manifests |
736
+ | `--cwd <dir>` | Git working directory (default: `.`) |
737
+
738
+ **Restore flags:**
739
+
740
+ | Flag | Description |
741
+ | --------------------------------- | -------------------------------------------------------------------------------------------- |
742
+ | `--out <path>` | Non-empty output file path (required) |
743
+ | `--slug <slug>` | Resolve tree OID from vault slug |
744
+ | `--oid <tree-oid>` | Direct tree OID |
745
+ | `--key-file <path>` | Encryption key file |
746
+ | `--vault-passphrase <pass>` | Inline vault passphrase (accepted with warning; prefer file/stdin, env, or keychain sources) |
747
+ | `--vault-passphrase-file <path>` | Read passphrase from file (`-` for stdin) |
748
+ | `--os-keychain-target <target>` | OS keychain passphrase source |
749
+ | `--os-keychain-account <account>` | Keychain account namespace |
750
+ | `--concurrency <n>` | Parallel chunk I/O |
751
+ | `--max-restore-buffer <n>` | Max buffered restore size in bytes |
752
+ | `--cwd <dir>` | Git working directory |
753
+
754
+ ### Vault Commands
755
+
756
+ | Command | Description |
757
+ | ----------------------------- | ------------------------------------- |
758
+ | `git-cas vault init` | Initialize the vault |
759
+ | `git-cas vault list` | List all vault entries |
760
+ | `git-cas vault remove <slug>` | Remove a vault entry |
761
+ | `git-cas vault info <slug>` | Show info for a vault entry |
762
+ | `git-cas vault stats` | Vault size, dedup, encryption summary |
763
+ | `git-cas vault history` | Show vault commit history |
764
+ | `git-cas vault rotate` | Rotate vault passphrase |
765
+ | `git-cas vault dashboard` | Interactive TUI explorer |
766
+
767
+ **Vault init flags:**
768
+
769
+ | Flag | Description |
770
+ | -------------------------------- | ------------------------------------------------------------------------ |
771
+ | `--vault-passphrase <pass>` | Enable encrypted vault from an inline passphrase (accepted with warning) |
772
+ | `--vault-passphrase-file <path>` | Read passphrase from file (`-` for stdin) |
773
+ | `--os-keychain-target <target>` | OS keychain passphrase source |
774
+ | `--algorithm <pbkdf2\|scrypt>` | KDF algorithm |
775
+
776
+ **Vault rotate flags:**
777
+
778
+ | Flag | Description |
779
+ | ------------------------------ | ------------------------------------------------------- |
780
+ | `--old-passphrase <pass>` | Current inline vault passphrase (accepted with warning) |
781
+ | `--new-passphrase <pass>` | New inline vault passphrase (accepted with warning) |
782
+ | `--old-passphrase-file <path>` | Read old passphrase from file (`-` for stdin) |
783
+ | `--new-passphrase-file <path>` | Read new passphrase from file (`-` for stdin) |
784
+ | `--algorithm <pbkdf2\|scrypt>` | KDF algorithm for new passphrase |
785
+
786
+ ### Inspection and Verification
787
+
788
+ | Command | Description |
789
+ | -------------------------------------------- | ----------------------------------------- |
790
+ | `git-cas inspect --slug <slug>` | Inspect manifest (human-readable or JSON) |
791
+ | `git-cas inspect --oid <tree-oid> --heatmap` | Chunk size heatmap visualization |
792
+ | `git-cas verify --slug <slug>` | Verify chunk-level SHA-256 integrity |
793
+ | `git-cas doctor` | Vault health report |
794
+ | `git-cas tree --manifest <path>` | Create Git tree from manifest JSON file |
795
+
796
+ ### Key and Recipient Management
797
+
798
+ | Command | Description |
799
+ | ------------------------------------------------------------------------------------------- | --------------------- |
800
+ | `git-cas rotate --slug <slug> --old-key-file <path> --new-key-file <path>` | Rotate encryption key |
801
+ | `git-cas recipient add <slug> --label <label> --key-file <path> --existing-key-file <path>` | Add recipient |
802
+ | `git-cas recipient remove <slug> --label <label>` | Remove recipient |
803
+ | `git-cas recipient list <slug>` | List recipients |
804
+
805
+ ### Agent CLI
806
+
807
+ Machine-facing commands for CI/CD and agentic workflows. The agent CLI returns newline-delimited protocol events on stdout and exits with stable status codes. It accepts the same core targets and credential sources as the human CLI.
808
+
809
+ | Command | Description |
810
+ | ----------------------------------------------------- | ---------------------------------------------- |
811
+ | `git-cas agent store <file> --slug <slug> --tree` | Store an asset and optionally vault it |
812
+ | `git-cas agent tree --manifest <path>` | Create a Git tree from manifest JSON |
813
+ | `git-cas agent restore --slug <slug> --out <path>` | Restore from a vault slug |
814
+ | `git-cas agent restore --oid <tree-oid> --out <path>` | Restore from a direct tree OID |
815
+ | `git-cas agent inspect --slug <slug>` | Return manifest JSON for a target |
816
+ | `git-cas agent verify --slug <slug>` | Verify integrity and return an agent exit code |
817
+ | `git-cas agent doctor` | Return a vault health report |
818
+ | `git-cas agent rotate --slug <slug>` | Rotate a recipient/key wrapper |
819
+ | `git-cas agent recipient add <slug>` | Add an envelope recipient |
820
+ | `git-cas agent recipient remove <slug>` | Remove an envelope recipient |
821
+ | `git-cas agent recipient list <slug>` | List envelope recipients |
822
+ | `git-cas agent vault init` | Initialize the vault |
823
+ | `git-cas agent vault list` | List vault entries |
824
+ | `git-cas agent vault info <slug>` | Inspect a vault entry |
825
+ | `git-cas agent vault history` | Return vault history |
826
+ | `git-cas agent vault remove <slug>` | Remove a vault entry |
827
+ | `git-cas agent vault rotate` | Rotate the vault passphrase |
828
+ | `git-cas agent vault stats` | Return vault size/dedupe/encryption stats |
829
+
830
+ Use `--request <json>` or stdin JSON for structured request payloads where a workflow needs machine-built inputs. See [docs/API.md](./docs/API.md) for the detailed protocol fields and response schemas.
831
+
832
+ ---
833
+
834
+ ## Configuration Reference
835
+
836
+ ### Constructor Options
837
+
838
+ This table describes the high-level `ContentAddressableStore` facade. The facade supplies `FixedChunker`, `NodeCompressionAdapter`, runtime crypto, and the package `formatVersion` automatically when those options are omitted. If you construct `CasService` directly, `chunker` and `compressionAdapter` are required injections; see [ADVANCED_GUIDE.md](./ADVANCED_GUIDE.md#direct-casservice-and-custom-port-contracts).
839
+
840
+ | Option | Type | Default | Description |
841
+ | ---------------------- | ------------------- | ------------------------ | --------------------------------------------------------------------------------------------------- |
842
+ | `plumbing` | `GitPlumbing` | (required) | `@git-stunts/plumbing` instance |
843
+ | `chunkSize` | `number` | `262144` (256 KiB) | Chunk size in bytes (min 1024, max 100 MiB) |
844
+ | `codec` | `CodecPort` | `JsonCodec` | Manifest serialization codec |
845
+ | `crypto` | `CryptoPort` | Auto-detected | Crypto adapter (Node or WebCrypto) |
846
+ | `observability` | `ObservabilityPort` | `SilentObserver` | Metrics, logs, spans |
847
+ | `policy` | `Policy` | None | `@git-stunts/alfred` resilience policy |
848
+ | `merkleThreshold` | `number` | `1000` | Chunk count above which Merkle sub-manifests are used |
849
+ | `concurrency` | `number` | `1` | Parallel chunk I/O operations (max 64); values > 1 enable parallel chunk restore |
850
+ | `chunking` | `object` | None | Chunking strategy config (see below) |
851
+ | `chunker` | `ChunkingPort` | `FixedChunker` | Pre-built chunker instance (advanced) |
852
+ | `maxRestoreBufferSize` | `number` | `536870912` (512 MiB) | Max bytes for buffered restore |
853
+ | `compressionAdapter` | `CompressionPort` | `NodeCompressionAdapter` | Compression adapter |
854
+ | `formatVersion` | `string` | Package version | Semver string stamped into new manifests by the facade. Directly configurable only on `CasService`. |
855
+
856
+ ### Encryption Options (Store)
857
+
858
+ | Key | Type | Default | Description |
859
+ | ------------ | ------------------------------------- | ------------------------------------- | --------------------------------------------------------------- |
860
+ | `scheme` | `'whole' \| 'framed' \| 'convergent'` | `convergent` (CDC) / `framed` (fixed) | Encryption scheme |
861
+ | `frameBytes` | `number` | `65536` (64 KiB) | Frame size for `framed` scheme (max 64 MiB) |
862
+ | `convergent` | `boolean` | Auto | Explicit convergent opt-in/opt-out when no `scheme` is provided |
863
+
864
+ ### Chunking Config Object
865
+
866
+ Constructor `chunking` sets the facade default. `store()` and `storeFile()` can
867
+ also receive the same object as a per-operation override.
868
+
869
+ | Key | Type | Description |
870
+ | ----------------- | ------------------ | -------------------------------------- |
871
+ | `strategy` | `'fixed' \| 'cdc'` | Chunking strategy |
872
+ | `chunkSize` | `number` | Fixed chunk size (fixed strategy only) |
873
+ | `targetChunkSize` | `number` | CDC target chunk size |
874
+ | `minChunkSize` | `number` | CDC minimum chunk size |
875
+ | `maxChunkSize` | `number` | CDC maximum chunk size |
876
+ | `normalized` | `boolean` | Use FastCDC-style dual-mask boundaries |
877
+
878
+ ### `.casrc` Project Config
879
+
880
+ Place a `.casrc` JSON file at your repository root to set defaults. CLI flags always override `.casrc` values.
881
+
882
+ ```json
883
+ {
884
+ "chunkSize": 131072,
885
+ "strategy": "cdc",
886
+ "concurrency": 4,
887
+ "codec": "cbor",
888
+ "compression": "gzip",
889
+ "merkleThreshold": 500,
890
+ "maxRestoreBufferSize": 268435456,
891
+ "cdc": {
892
+ "targetChunkSize": 65536,
893
+ "minChunkSize": 16384,
894
+ "maxChunkSize": 262144
895
+ }
896
+ }
897
+ ```
898
+
899
+ ### Environment Variables
900
+
901
+ | Variable | Description |
902
+ | -------------------- | ----------------------------------------------------------- |
903
+ | `GIT_CAS_PASSPHRASE` | Vault passphrase (preferred over `--vault-passphrase` flag) |
904
+
905
+ ---
906
+
907
+ ## Architecture
908
+
909
+ `git-cas` follows hexagonal architecture with four tiers:
910
+
911
+ 1. **Facade** (`index.js`) -- Public entry point. Manages lazy initialization and adaptive crypto.
912
+ 2. **CasService** (`src/domain/services/CasService.js`) -- Lean domain
913
+ facade. Selects store/restore strategies, coordinates injected ports, and
914
+ delegates byte-level work to domain services and strategy entities.
915
+ 3. **VaultService** (`src/domain/services/VaultService.js`) -- Vault use-case
916
+ orchestrator. Delegates Git persistence, parse caching, metadata/tree codecs,
917
+ privacy indexing, key verification, and retry timing to cohesive collaborators.
918
+ 4. **Ports** -- Pure interfaces isolating the domain from I/O: `GitPersistencePort`, `CryptoPort`, `ChunkingPort`, `CompressionPort`, `ObservabilityPort`.
919
+
920
+ Adapters implement ports for specific runtimes: `GitPersistenceAdapter` (shells out to `git` via `@git-stunts/plumbing`), `NodeCryptoAdapter`, `NodeCompressionAdapter`, etc.
921
+
922
+ For the full architecture breakdown, see [ARCHITECTURE.md](./ARCHITECTURE.md).
923
+
924
+ ---
925
+
926
+ **Tests are the spec. Every feature is defined by its tests.**