@git-stunts/git-cas 5.3.2 → 6.0.0

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 +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +393 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +872 -0
  6. package/README.md +219 -325
  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 +998 -214
  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 +296 -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 +2224 -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 +208 -65
  60. package/index.js +163 -54
  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 +123 -38
  103. package/src/domain/services/CasService.js +298 -834
  104. package/src/domain/services/ChunkRepository.js +230 -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 +178 -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 +3 -1
  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,872 @@
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
+ Embed content-addressed storage into your JavaScript/TypeScript application.
18
+ - Start with [Library Quick Start](#library-quick-start) below.
19
+ - Understand the port/adapter model: [ARCHITECTURE.md](./ARCHITECTURE.md).
20
+ - Custom adapters: [docs/EXTENDING.md](./docs/EXTENDING.md).
21
+
22
+ ### 2. CLI / TUI Usage
23
+ Store, restore, and manage assets from the terminal.
24
+ - Jump to [CLI Reference](#cli-reference).
25
+ - Interactive explorer: `git-cas vault dashboard`.
26
+
27
+ ### 3. Agentic Automation
28
+ Machine-facing agent CLI for structured CI/CD or agentic workflows.
29
+ - [docs/API.md](./docs/API.md) for the agent command surface.
30
+ - Run: `git-cas agent <command>`.
31
+
32
+ ### 4. Contributing
33
+ - Read `METHOD.md` and `BEARING.md` for project process.
34
+ - See [Architecture](#architecture) for orientation.
35
+
36
+ ---
37
+
38
+ ## Feature Coverage Map
39
+
40
+ This guide and [ADVANCED_GUIDE.md](./ADVANCED_GUIDE.md) are the complete
41
+ feature coverage pair. The quick path lives here; implementation mechanics,
42
+ limits, and port contracts live in the advanced guide.
43
+
44
+ | Feature Area | Covered Here | Advanced Coverage |
45
+ |---|---|---|
46
+ | 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) |
47
+ | 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) |
48
+ | 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) |
49
+ | 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) |
50
+ | Fixed chunking, CDC, FastCDC normalization | [Chunking](#chunking) | [Content-Defined Chunking (CDC)](./ADVANCED_GUIDE.md#content-defined-chunking-cdc) |
51
+ | 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) |
52
+ | Passphrases, PBKDF2, scrypt, KDF policy | [Passphrase-Based Encryption](#passphrase-based-encryption) | [KDF Policy](./ADVANCED_GUIDE.md#kdf-policy) |
53
+ | 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) |
54
+ | 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) |
55
+ | Compression and custom adapters | [Compression](#compression) | [CompressionPort Architecture](./ADVANCED_GUIDE.md#compressionport-architecture) |
56
+ | 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) |
57
+ | 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) |
58
+ | Human CLI, TUI dashboard, agent CLI | [CLI Reference](#cli-reference) | [Operational Tooling](./ADVANCED_GUIDE.md#operational-tooling) |
59
+ | 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) |
60
+ | Release verification, migration, build stamping | [Migrating Legacy Encryption Schemes](#migrating-legacy-encryption-schemes) | [Operational Tooling](./ADVANCED_GUIDE.md#operational-tooling) |
61
+
62
+ ---
63
+
64
+ ## Library Quick Start
65
+
66
+ A complete init-store-tree-restore cycle:
67
+
68
+ ```js
69
+ import ContentAddressableStore from '@git-stunts/git-cas';
70
+
71
+ // 1. Initialize
72
+ const cas = await ContentAddressableStore.open({ cwd: '/path/to/repo' });
73
+
74
+ // 2. Store a file
75
+ const manifest = await cas.storeFile({
76
+ filePath: './photo.jpg',
77
+ slug: 'photos/vacation',
78
+ });
79
+
80
+ // 3. Create a Git tree (persists the manifest + chunks as a tree object)
81
+ const treeOid = await cas.createTree({ manifest });
82
+
83
+ // 4. Add to the vault index (GC-safe ref)
84
+ await cas.addToVault({ slug: 'photos/vacation', treeOid });
85
+
86
+ // 5. Restore later
87
+ const readBack = await cas.readManifest({ treeOid });
88
+ const { buffer } = await cas.restore({ manifest: readBack });
89
+ ```
90
+
91
+ ### Factory Methods
92
+
93
+ | Factory | Codec | Use Case |
94
+ |---|---|---|
95
+ | `await ContentAddressableStore.open({ cwd })` | JSON | Shortest normal application setup |
96
+ | `ContentAddressableStore.createJson({ plumbing })` | JSON | Human-readable manifests, debugging |
97
+ | `ContentAddressableStore.createCbor({ plumbing })` | CBOR | Compact binary manifests, production |
98
+
99
+ `open()` is async and accepts `cwd` plus the same facade options as the
100
+ constructor except `plumbing`. Use `createJson()` or `createCbor()` when you
101
+ already have a custom Git plumbing instance. Both explicit-plumbing factories
102
+ accept the same facade options as the constructor except `codec`, which is fixed
103
+ by the factory name.
104
+
105
+ ### Full Constructor
106
+
107
+ For complete control, use the constructor directly:
108
+
109
+ ```js
110
+ import ContentAddressableStore, {
111
+ CborCodec,
112
+ EventEmitterObserver,
113
+ CdcChunker,
114
+ NodeCompressionAdapter,
115
+ } from '@git-stunts/git-cas';
116
+
117
+ const cas = new ContentAddressableStore({
118
+ plumbing,
119
+ chunkSize: 128 * 1024, // 128 KiB chunks
120
+ codec: new CborCodec(),
121
+ observability: new EventEmitterObserver(),
122
+ merkleThreshold: 500, // Merkle sub-manifests above 500 chunks
123
+ concurrency: 4, // Parallel chunk I/O
124
+ maxRestoreBufferSize: 256 * 1024 * 1024, // 256 MiB buffer limit
125
+ compressionAdapter: new NodeCompressionAdapter(),
126
+ chunking: { // CDC chunking
127
+ strategy: 'cdc',
128
+ targetChunkSize: 64 * 1024,
129
+ minChunkSize: 16 * 1024,
130
+ maxChunkSize: 256 * 1024,
131
+ },
132
+ });
133
+ ```
134
+
135
+ ---
136
+
137
+ ## Store Operations
138
+
139
+ ### `store({ source, slug, filename })`
140
+
141
+ Stores data from any async iterable:
142
+
143
+ ```js
144
+ async function* generateData() {
145
+ yield new TextEncoder().encode('chunk one');
146
+ yield new TextEncoder().encode('chunk two');
147
+ }
148
+
149
+ const manifest = await cas.store({
150
+ source: generateData(),
151
+ slug: 'data/stream-example',
152
+ filename: 'output.bin',
153
+ });
154
+ ```
155
+
156
+ ### `storeFile({ filePath, slug })`
157
+
158
+ Convenience method that reads a file from disk:
159
+
160
+ ```js
161
+ const manifest = await cas.storeFile({
162
+ filePath: '/absolute/path/to/archive.tar.gz',
163
+ slug: 'backups/2026-04-23',
164
+ });
165
+ ```
166
+
167
+ The filename defaults to the basename of `filePath`. Override it with the optional `filename` parameter.
168
+
169
+ ---
170
+
171
+ ## Encryption
172
+
173
+ All store and restore methods accept encryption options. Encryption is AES-256-GCM.
174
+
175
+ ### Encryption Schemes
176
+
177
+ | Scheme | Description | Default When |
178
+ |---|---|---|
179
+ | `convergent` | Per-chunk encryption keyed by content hash; preserves CDC deduplication across encrypted stores | CDC chunking + encryption |
180
+ | `framed` | Streaming framed encryption with per-frame AAD binding to slug | Non-CDC encrypted stores |
181
+ | `whole` | Whole-object encryption with AAD binding to slug | Explicit only |
182
+
183
+ AAD (Additional Authenticated Data) is always on for `whole` and `framed` schemes, binding ciphertext to the asset slug.
184
+
185
+ **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`.
186
+
187
+ #### Legacy Schemes
188
+
189
+ 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.
190
+
191
+ ### Raw Key Encryption
192
+
193
+ ```js
194
+ import { randomBytes } from 'node:crypto';
195
+
196
+ const key = randomBytes(32); // 32-byte AES-256 key
197
+
198
+ // Store encrypted
199
+ const manifest = await cas.storeFile({
200
+ filePath: './secret.pdf',
201
+ slug: 'docs/secret',
202
+ encryptionKey: key,
203
+ });
204
+
205
+ // Restore encrypted
206
+ const treeOid = await cas.createTree({ manifest });
207
+ const readBack = await cas.readManifest({ treeOid });
208
+ const { buffer } = await cas.restore({
209
+ manifest: readBack,
210
+ encryptionKey: key,
211
+ });
212
+ ```
213
+
214
+ ### Passphrase-Based Encryption
215
+
216
+ Derives a key using PBKDF2 (default) or scrypt:
217
+
218
+ PBKDF2 works across Node, Bun, and Deno/Web Crypto. scrypt requires a Node/Bun
219
+ crypto adapter; Web Crypto runtimes report a capability error for scrypt.
220
+
221
+ ```js
222
+ // Store with passphrase (PBKDF2)
223
+ const pbkdf2Manifest = await cas.storeFile({
224
+ filePath: './secret.pdf',
225
+ slug: 'docs/secret',
226
+ passphrase: 'my-strong-passphrase',
227
+ });
228
+
229
+ // Store with scrypt
230
+ const scryptManifest = await cas.storeFile({
231
+ filePath: './secret.pdf',
232
+ slug: 'docs/secret',
233
+ passphrase: 'my-strong-passphrase',
234
+ kdfOptions: { algorithm: 'scrypt' },
235
+ });
236
+
237
+ // Restore with passphrase
238
+ const readBack = await cas.readManifest({ treeOid });
239
+ const { buffer } = await cas.restore({
240
+ manifest: readBack,
241
+ passphrase: 'my-strong-passphrase',
242
+ });
243
+ ```
244
+
245
+ ### Multi-Recipient (Envelope) Encryption
246
+
247
+ Envelope encryption wraps a random DEK with each recipient's KEK. Adding or removing recipients never re-encrypts the data.
248
+
249
+ ```js
250
+ import { randomBytes } from 'node:crypto';
251
+
252
+ const aliceKey = randomBytes(32);
253
+ const bobKey = randomBytes(32);
254
+
255
+ // Store with recipients
256
+ const manifest = await cas.storeFile({
257
+ filePath: './shared-doc.pdf',
258
+ slug: 'team/shared-doc',
259
+ recipients: [
260
+ { label: 'alice', key: aliceKey },
261
+ { label: 'bob', key: bobKey },
262
+ ],
263
+ });
264
+
265
+ // Restore using any recipient's key
266
+ const readBack = await cas.readManifest({ treeOid });
267
+ const { buffer } = await cas.restore({
268
+ manifest: readBack,
269
+ encryptionKey: aliceKey,
270
+ });
271
+
272
+ // Add a recipient
273
+ const updated = await cas.addRecipient({
274
+ manifest: readBack,
275
+ existingKey: aliceKey, // Any current recipient's key
276
+ newRecipientKey: carolKey,
277
+ label: 'carol',
278
+ });
279
+
280
+ // Remove a recipient
281
+ const shrunk = await cas.removeRecipient({
282
+ manifest: updated,
283
+ label: 'bob',
284
+ });
285
+
286
+ // List recipients
287
+ const labels = await cas.listRecipients(readBack);
288
+ // => ['alice', 'bob']
289
+
290
+ // Rotate a recipient's key (no data re-encryption)
291
+ const rotated = await cas.rotateKey({
292
+ manifest: readBack,
293
+ oldKey: aliceKey,
294
+ newKey: aliceNewKey,
295
+ label: 'alice', // Optional: target a specific recipient
296
+ });
297
+ ```
298
+
299
+ ### Explicit Scheme Selection
300
+
301
+ Override the default scheme:
302
+
303
+ ```js
304
+ // Force framed encryption (even with CDC chunking)
305
+ const framedManifest = await cas.storeFile({
306
+ filePath: './large-video.mp4',
307
+ slug: 'media/video',
308
+ encryptionKey: key,
309
+ encryption: {
310
+ scheme: 'framed', // 'whole', 'framed', or 'convergent'
311
+ frameBytes: 128 * 1024, // 128 KiB frames (framed scheme only)
312
+ },
313
+ });
314
+
315
+ // Force whole-object encryption
316
+ const wholeManifest = await cas.storeFile({
317
+ filePath: './small-config.json',
318
+ slug: 'config/app',
319
+ encryptionKey: key,
320
+ encryption: { scheme: 'whole' },
321
+ });
322
+ ```
323
+
324
+ ### Migrating Legacy Encryption Schemes
325
+
326
+ 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.
327
+
328
+ ```sh
329
+ node scripts/migrate-encryption.js
330
+ printf '%s\n' 'my-secret' | node scripts/migrate-encryption.js --execute --passphrase-file -
331
+ node scripts/migrate-encryption.js --execute --key-file ./asset.key
332
+ ```
333
+
334
+ 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.
335
+
336
+ ---
337
+
338
+ ## Chunking
339
+
340
+ Content is split into chunks before storage. Two strategies are available:
341
+
342
+ ### Fixed Chunking (Default)
343
+
344
+ Splits data into equal-sized chunks. Simple and predictable.
345
+
346
+ ```js
347
+ const cas = ContentAddressableStore.createJson({
348
+ plumbing,
349
+ chunkSize: 512 * 1024, // 512 KiB chunks
350
+ });
351
+ ```
352
+
353
+ ### Content-Defined Chunking (CDC)
354
+
355
+ Uses a rolling hash to find chunk boundaries based on content. Provides deduplication across similar files.
356
+
357
+ ```js
358
+ const cas = new ContentAddressableStore({
359
+ plumbing,
360
+ chunking: {
361
+ strategy: 'cdc',
362
+ targetChunkSize: 64 * 1024, // 64 KiB target
363
+ minChunkSize: 16 * 1024, // 16 KiB minimum
364
+ maxChunkSize: 256 * 1024, // 256 KiB maximum
365
+ },
366
+ });
367
+ ```
368
+
369
+ CDC parameters:
370
+
371
+ | Parameter | Description |
372
+ |---|---|
373
+ | `targetChunkSize` | Average chunk size the rolling hash targets |
374
+ | `minChunkSize` | Minimum chunk size (never split smaller) |
375
+ | `maxChunkSize` | Maximum chunk size (force split at this boundary) |
376
+
377
+ > **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.
378
+
379
+ ---
380
+
381
+ ## Compression
382
+
383
+ 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.
384
+
385
+ ### Library
386
+
387
+ ```js
388
+ const manifest = await cas.storeFile({
389
+ filePath: './large-log.txt',
390
+ slug: 'logs/2026-04-23',
391
+ compression: { algorithm: 'gzip' },
392
+ });
393
+
394
+ // Decompression is automatic on restore -- the manifest records the algorithm.
395
+ const { buffer } = await cas.restore({ manifest: readBack });
396
+ ```
397
+
398
+ ### Custom Compression Adapter
399
+
400
+ Implement the `CompressionPort` interface to use a different algorithm:
401
+
402
+ ```js
403
+ import { CompressionPort } from '@git-stunts/git-cas';
404
+
405
+ class BrotliAdapter extends CompressionPort {
406
+ async compressBuffer(buffer) { /* ... */ }
407
+ async decompressBuffer(buffer) { /* ... */ }
408
+ async *compressStream(source) { /* ... */ }
409
+ async *decompressStream(source) { /* ... */ }
410
+ }
411
+
412
+ const cas = new ContentAddressableStore({
413
+ plumbing,
414
+ compressionAdapter: new BrotliAdapter(),
415
+ });
416
+ ```
417
+
418
+ ---
419
+
420
+ ## Manifest Diffing
421
+
422
+ 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.
423
+
424
+ ### Library
425
+
426
+ ```js
427
+ // Static method (requires class, not an instance)
428
+ import CasService from '@git-stunts/git-cas/service';
429
+ const serviceDiff = CasService.diffManifests(oldManifest, newManifest);
430
+
431
+ // Standalone function
432
+ import { diffManifests } from '@git-stunts/git-cas';
433
+ const standaloneDiff = diffManifests(oldManifest, newManifest);
434
+
435
+ console.log(standaloneDiff.summary);
436
+ // => {
437
+ // addedCount: 3, removedCount: 1, unchangedCount: 42,
438
+ // addedBytes: 196608, removedBytes: 65536, unchangedBytes: 2752512,
439
+ // }
440
+ console.log(standaloneDiff.added); // Chunk[] -- new chunks in newManifest
441
+ console.log(standaloneDiff.removed); // Chunk[] -- chunks only in oldManifest
442
+ console.log(standaloneDiff.unchanged); // Chunk[] -- chunks in both (by digest)
443
+ ```
444
+
445
+ ---
446
+
447
+ ## Vault Management
448
+
449
+ 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.
450
+
451
+ ### Initialize the Vault
452
+
453
+ ```js
454
+ // Plain vault (no encryption)
455
+ await cas.initVault();
456
+
457
+ // Encrypted vault with passphrase
458
+ await cas.initVault({
459
+ passphrase: 'vault-secret',
460
+ kdfOptions: { algorithm: 'pbkdf2' }, // or 'scrypt'
461
+ });
462
+
463
+ // Encrypted vault with privacy mode
464
+ await cas.initVault({
465
+ passphrase: 'vault-secret',
466
+ kdfOptions: { algorithm: 'pbkdf2' },
467
+ privacy: true,
468
+ });
469
+ ```
470
+
471
+ ### Add, List, Resolve, Remove
472
+
473
+ ```js
474
+ // Add an entry
475
+ await cas.addToVault({ slug: 'photos/vacation', treeOid });
476
+
477
+ // Overwrite an existing entry
478
+ await cas.addToVault({ slug: 'photos/vacation', treeOid: newTreeOid, force: true });
479
+
480
+ // List all entries
481
+ const entries = await cas.listVault();
482
+ // => [{ slug: 'photos/vacation', treeOid: 'abc123...' }, ...]
483
+
484
+ // Resolve a single slug to its tree OID
485
+ const oid = await cas.resolveVaultEntry({ slug: 'photos/vacation' });
486
+
487
+ // Remove an entry
488
+ const { commitOid, removedTreeOid } = await cas.removeFromVault({
489
+ slug: 'photos/vacation',
490
+ });
491
+ ```
492
+
493
+ ### Rotate Vault Passphrase
494
+
495
+ Re-wraps every envelope-encrypted entry's DEK with a new key derived from `newPassphrase`. Entries using direct-key encryption are skipped.
496
+
497
+ ```js
498
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase({
499
+ oldPassphrase: 'old-secret',
500
+ newPassphrase: 'new-secret',
501
+ kdfOptions: { algorithm: 'scrypt' }, // optional: change KDF algorithm
502
+ });
503
+ ```
504
+
505
+ ### Get Vault Metadata
506
+
507
+ ```js
508
+ const metadata = await cas.getVaultMetadata();
509
+ // => { version: 1, encryption: { cipher: 'aes-256-gcm', kdf: { ... }, verifier: { ... } } }
510
+ ```
511
+
512
+ Encrypted v6 vaults include a verifier in `.vault.json`, so tools can reject a
513
+ wrong passphrase even before the vault contains entries. Normal CLI and facade
514
+ flows verify derived vault keys automatically. Custom tools that derive vault
515
+ keys themselves should call `verifyVaultKey({ encryptionKey })` before using the
516
+ key.
517
+
518
+ ---
519
+
520
+ ## Vault Privacy Mode
521
+
522
+ 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.
523
+
524
+ ### Enabling Privacy Mode
525
+
526
+ Privacy mode requires vault-level encryption. Enable it at vault initialization:
527
+
528
+ ```js
529
+ await cas.initVault({
530
+ passphrase: 'vault-secret',
531
+ kdfOptions: { algorithm: 'pbkdf2' },
532
+ privacy: true,
533
+ });
534
+ ```
535
+
536
+ ### Limitations
537
+
538
+ - Privacy mode cannot be enabled on an existing vault -- it must be set at init time.
539
+ - All vault read operations that need to resolve slugs require the encryption key, since the slug-to-HMAC mapping is itself encrypted.
540
+ - Privacy mode adds overhead: an encrypted `.privacy-index` blob is maintained alongside the vault tree.
541
+
542
+ ---
543
+
544
+ ## Manifest Features
545
+
546
+ ### Manifest Versions and Format Version
547
+
548
+ Manifests are versioned value objects that describe a stored asset:
549
+
550
+ - **v1**: Flat chunk list with SHA-256 integrity hashes.
551
+ - **v2**: Merkle sub-manifest support for large files. Activated when chunk count exceeds `merkleThreshold` (default 1000).
552
+
553
+ 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.
554
+
555
+ ### Reading a Manifest
556
+
557
+ ```js
558
+ const manifest = await cas.readManifest({ treeOid });
559
+
560
+ console.log(manifest.slug); // 'photos/vacation'
561
+ console.log(manifest.filename); // 'photo.jpg'
562
+ console.log(manifest.size); // total bytes
563
+ console.log(manifest.chunks.length); // number of chunks
564
+ console.log(manifest.encryption); // encryption metadata or undefined
565
+ console.log(manifest.compression); // compression metadata or undefined
566
+ console.log(manifest.formatVersion); // '6.0.0' or undefined (older manifests)
567
+ ```
568
+
569
+ ### Inspecting an Asset
570
+
571
+ Returns metadata without performing a full restore:
572
+
573
+ ```js
574
+ const info = await cas.inspectAsset({ treeOid });
575
+ // => { slug: 'photos/vacation', chunksOrphaned: 4 }
576
+ ```
577
+
578
+ ### Integrity Verification
579
+
580
+ Verifies every chunk's SHA-256 hash against the manifest:
581
+
582
+ ```js
583
+ const ok = await cas.verifyIntegrity(manifest);
584
+ if (!ok) {
585
+ console.error('Integrity check failed -- data may be corrupted');
586
+ }
587
+ ```
588
+
589
+ ---
590
+
591
+ ## Restore Modes
592
+
593
+ Three restore modes serve different use cases. When `concurrency` is greater than 1, chunk reads are parallelized for faster restore.
594
+
595
+ ### `restore({ manifest })` -- Buffered to Memory
596
+
597
+ Returns the entire file as a single buffer. Best for small-to-medium files.
598
+
599
+ ```js
600
+ const manifest = await cas.readManifest({ treeOid });
601
+ const { buffer, bytesWritten } = await cas.restore({ manifest });
602
+ ```
603
+
604
+ Encrypted content requires a key:
605
+
606
+ ```js
607
+ const { buffer } = await cas.restore({
608
+ manifest,
609
+ encryptionKey: key,
610
+ // or: passphrase: 'secret',
611
+ });
612
+ ```
613
+
614
+ The `maxRestoreBufferSize` option (default 512 MiB) guards against out-of-memory errors.
615
+
616
+ ### `restoreFile({ manifest, outputPath, baseDirectory })` -- Atomic File Write
617
+
618
+ Writes directly to disk. Handles streaming internally for framed-encrypted and compressed content.
619
+
620
+ ```js
621
+ const manifest = await cas.readManifest({ treeOid });
622
+ const { bytesWritten } = await cas.restoreFile({
623
+ manifest,
624
+ outputPath: '/tmp/restored-photo.jpg',
625
+ baseDirectory: '/tmp',
626
+ encryptionKey: key, // if encrypted
627
+ });
628
+ ```
629
+
630
+ ### `restoreStream({ manifest })` -- Async Iterable
631
+
632
+ Returns an async iterable of `Uint8Array` chunks. Best for large files, piping to other streams, or memory-constrained environments.
633
+
634
+ ```js
635
+ const manifest = await cas.readManifest({ treeOid });
636
+
637
+ for await (const chunk of cas.restoreStream({ manifest, encryptionKey: key })) {
638
+ process.stdout.write(chunk);
639
+ }
640
+ ```
641
+
642
+ ### When to Use Each
643
+
644
+ | Mode | Memory | Streaming | Use Case |
645
+ |---|---|---|---|
646
+ | `restore` | Full file in RAM | No | Small files, in-memory processing |
647
+ | `restoreFile` | Low | Yes (internal) | Disk targets, atomic writes |
648
+ | `restoreStream` | Low | Yes (external) | Pipes, HTTP responses, large files |
649
+
650
+ ---
651
+
652
+ ## CLI Reference
653
+
654
+ All commands support `--json` for machine-readable output and `--quiet` to suppress progress.
655
+
656
+ ### Store and Restore
657
+
658
+ | Command | Description |
659
+ |---|---|
660
+ | `git-cas store <file> --slug <slug>` | Store a file into Git CAS |
661
+ | `git-cas restore --out <path> --slug <slug>` | Restore a file from vault slug |
662
+ | `git-cas restore --out <path> --oid <tree-oid>` | Restore a file from tree OID |
663
+
664
+ **Store flags:**
665
+
666
+ | Flag | Description |
667
+ |---|---|
668
+ | `--slug <slug>` | Asset slug identifier (required) |
669
+ | `--tree` | Create Git tree and add to vault |
670
+ | `--force` | Overwrite existing vault entry (requires `--tree`) |
671
+ | `--key-file <path>` | Path to 32-byte raw encryption key file |
672
+ | `--recipient <label:keyfile>` | Envelope recipient (repeatable) |
673
+ | `--vault-passphrase <pass>` | Inline vault passphrase (accepted with warning; prefer `--vault-passphrase-file -`, `GIT_CAS_PASSPHRASE`, or `--os-keychain-target`) |
674
+ | `--vault-passphrase-file <path>` | Read passphrase from file (`-` for stdin) |
675
+ | `--os-keychain-target <target>` | Read passphrase from OS keychain via `@git-stunts/vault` |
676
+ | `--os-keychain-account <account>` | Keychain account namespace (default: `git-cas`) |
677
+ | `--gzip` | Enable gzip compression |
678
+ | `--strategy <fixed\|cdc>` | Chunking strategy |
679
+ | `--chunk-size <n>` | Chunk size in bytes |
680
+ | `--target-chunk-size <n>` | CDC target chunk size |
681
+ | `--min-chunk-size <n>` | CDC minimum chunk size |
682
+ | `--max-chunk-size <n>` | CDC maximum chunk size |
683
+ | `--concurrency <n>` | Parallel chunk I/O operations |
684
+ | `--codec <json\|cbor>` | Manifest codec |
685
+ | `--merkle-threshold <n>` | Chunk count for Merkle sub-manifests |
686
+ | `--cwd <dir>` | Git working directory (default: `.`) |
687
+
688
+ **Restore flags:**
689
+
690
+ | Flag | Description |
691
+ |---|---|
692
+ | `--out <path>` | Non-empty output file path (required) |
693
+ | `--slug <slug>` | Resolve tree OID from vault slug |
694
+ | `--oid <tree-oid>` | Direct tree OID |
695
+ | `--key-file <path>` | Encryption key file |
696
+ | `--vault-passphrase <pass>` | Inline vault passphrase (accepted with warning; prefer file/stdin, env, or keychain sources) |
697
+ | `--vault-passphrase-file <path>` | Read passphrase from file (`-` for stdin) |
698
+ | `--os-keychain-target <target>` | OS keychain passphrase source |
699
+ | `--os-keychain-account <account>` | Keychain account namespace |
700
+ | `--concurrency <n>` | Parallel chunk I/O |
701
+ | `--max-restore-buffer <n>` | Max buffered restore size in bytes |
702
+ | `--cwd <dir>` | Git working directory |
703
+
704
+ ### Vault Commands
705
+
706
+ | Command | Description |
707
+ |---|---|
708
+ | `git-cas vault init` | Initialize the vault |
709
+ | `git-cas vault list` | List all vault entries |
710
+ | `git-cas vault remove <slug>` | Remove a vault entry |
711
+ | `git-cas vault info <slug>` | Show info for a vault entry |
712
+ | `git-cas vault stats` | Vault size, dedup, encryption summary |
713
+ | `git-cas vault history` | Show vault commit history |
714
+ | `git-cas vault rotate` | Rotate vault passphrase |
715
+ | `git-cas vault dashboard` | Interactive TUI explorer |
716
+
717
+ **Vault init flags:**
718
+
719
+ | Flag | Description |
720
+ |---|---|
721
+ | `--vault-passphrase <pass>` | Enable encrypted vault from an inline passphrase (accepted with warning) |
722
+ | `--vault-passphrase-file <path>` | Read passphrase from file (`-` for stdin) |
723
+ | `--os-keychain-target <target>` | OS keychain passphrase source |
724
+ | `--algorithm <pbkdf2\|scrypt>` | KDF algorithm |
725
+
726
+ **Vault rotate flags:**
727
+
728
+ | Flag | Description |
729
+ |---|---|
730
+ | `--old-passphrase <pass>` | Current inline vault passphrase (accepted with warning) |
731
+ | `--new-passphrase <pass>` | New inline vault passphrase (accepted with warning) |
732
+ | `--old-passphrase-file <path>` | Read old passphrase from file (`-` for stdin) |
733
+ | `--new-passphrase-file <path>` | Read new passphrase from file (`-` for stdin) |
734
+ | `--algorithm <pbkdf2\|scrypt>` | KDF algorithm for new passphrase |
735
+
736
+ ### Inspection and Verification
737
+
738
+ | Command | Description |
739
+ |---|---|
740
+ | `git-cas inspect --slug <slug>` | Inspect manifest (human-readable or JSON) |
741
+ | `git-cas inspect --oid <tree-oid> --heatmap` | Chunk size heatmap visualization |
742
+ | `git-cas verify --slug <slug>` | Verify chunk-level SHA-256 integrity |
743
+ | `git-cas doctor` | Vault health report |
744
+ | `git-cas tree --manifest <path>` | Create Git tree from manifest JSON file |
745
+
746
+ ### Key and Recipient Management
747
+
748
+ | Command | Description |
749
+ |---|---|
750
+ | `git-cas rotate --slug <slug> --old-key-file <path> --new-key-file <path>` | Rotate encryption key |
751
+ | `git-cas recipient add <slug> --label <label> --key-file <path> --existing-key-file <path>` | Add recipient |
752
+ | `git-cas recipient remove <slug> --label <label>` | Remove recipient |
753
+ | `git-cas recipient list <slug>` | List recipients |
754
+
755
+ ### Agent CLI
756
+
757
+ 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.
758
+
759
+ | Command | Description |
760
+ |---|---|
761
+ | `git-cas agent store <file> --slug <slug> --tree` | Store an asset and optionally vault it |
762
+ | `git-cas agent tree --manifest <path>` | Create a Git tree from manifest JSON |
763
+ | `git-cas agent restore --slug <slug> --out <path>` | Restore from a vault slug |
764
+ | `git-cas agent restore --oid <tree-oid> --out <path>` | Restore from a direct tree OID |
765
+ | `git-cas agent inspect --slug <slug>` | Return manifest JSON for a target |
766
+ | `git-cas agent verify --slug <slug>` | Verify integrity and return an agent exit code |
767
+ | `git-cas agent doctor` | Return a vault health report |
768
+ | `git-cas agent rotate --slug <slug>` | Rotate a recipient/key wrapper |
769
+ | `git-cas agent recipient add <slug>` | Add an envelope recipient |
770
+ | `git-cas agent recipient remove <slug>` | Remove an envelope recipient |
771
+ | `git-cas agent recipient list <slug>` | List envelope recipients |
772
+ | `git-cas agent vault init` | Initialize the vault |
773
+ | `git-cas agent vault list` | List vault entries |
774
+ | `git-cas agent vault info <slug>` | Inspect a vault entry |
775
+ | `git-cas agent vault history` | Return vault history |
776
+ | `git-cas agent vault remove <slug>` | Remove a vault entry |
777
+ | `git-cas agent vault rotate` | Rotate the vault passphrase |
778
+ | `git-cas agent vault stats` | Return vault size/dedupe/encryption stats |
779
+
780
+ 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.
781
+
782
+ ---
783
+
784
+ ## Configuration Reference
785
+
786
+ ### Constructor Options
787
+
788
+ 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).
789
+
790
+ | Option | Type | Default | Description |
791
+ |---|---|---|---|
792
+ | `plumbing` | `GitPlumbing` | (required) | `@git-stunts/plumbing` instance |
793
+ | `chunkSize` | `number` | `262144` (256 KiB) | Chunk size in bytes (min 1024, max 100 MiB) |
794
+ | `codec` | `CodecPort` | `JsonCodec` | Manifest serialization codec |
795
+ | `crypto` | `CryptoPort` | Auto-detected | Crypto adapter (Node or WebCrypto) |
796
+ | `observability` | `ObservabilityPort` | `SilentObserver` | Metrics, logs, spans |
797
+ | `policy` | `Policy` | None | `@git-stunts/alfred` resilience policy |
798
+ | `merkleThreshold` | `number` | `1000` | Chunk count above which Merkle sub-manifests are used |
799
+ | `concurrency` | `number` | `1` | Parallel chunk I/O operations (max 64); values > 1 enable parallel chunk restore |
800
+ | `chunking` | `object` | None | Chunking strategy config (see below) |
801
+ | `chunker` | `ChunkingPort` | `FixedChunker` | Pre-built chunker instance (advanced) |
802
+ | `maxRestoreBufferSize` | `number` | `536870912` (512 MiB) | Max bytes for buffered restore |
803
+ | `compressionAdapter` | `CompressionPort` | `NodeCompressionAdapter` | Compression adapter |
804
+ | `formatVersion` | `string` | Package version | Semver string stamped into new manifests by the facade. Directly configurable only on `CasService`. |
805
+
806
+ ### Encryption Options (Store)
807
+
808
+ | Key | Type | Default | Description |
809
+ |---|---|---|---|
810
+ | `scheme` | `'whole' \| 'framed' \| 'convergent'` | `convergent` (CDC) / `framed` (fixed) | Encryption scheme |
811
+ | `frameBytes` | `number` | `65536` (64 KiB) | Frame size for `framed` scheme (max 64 MiB) |
812
+ | `convergent` | `boolean` | Auto | Explicit convergent opt-in/opt-out when no `scheme` is provided |
813
+
814
+ ### Chunking Config Object
815
+
816
+ | Key | Type | Description |
817
+ |---|---|---|
818
+ | `strategy` | `'fixed' \| 'cdc'` | Chunking strategy |
819
+ | `chunkSize` | `number` | Fixed chunk size (fixed strategy only) |
820
+ | `targetChunkSize` | `number` | CDC target chunk size |
821
+ | `minChunkSize` | `number` | CDC minimum chunk size |
822
+ | `maxChunkSize` | `number` | CDC maximum chunk size |
823
+
824
+ ### `.casrc` Project Config
825
+
826
+ Place a `.casrc` JSON file at your repository root to set defaults. CLI flags always override `.casrc` values.
827
+
828
+ ```json
829
+ {
830
+ "chunkSize": 131072,
831
+ "strategy": "cdc",
832
+ "concurrency": 4,
833
+ "codec": "cbor",
834
+ "compression": "gzip",
835
+ "merkleThreshold": 500,
836
+ "maxRestoreBufferSize": 268435456,
837
+ "cdc": {
838
+ "targetChunkSize": 65536,
839
+ "minChunkSize": 16384,
840
+ "maxChunkSize": 262144
841
+ }
842
+ }
843
+ ```
844
+
845
+ ### Environment Variables
846
+
847
+ | Variable | Description |
848
+ |---|---|
849
+ | `GIT_CAS_PASSPHRASE` | Vault passphrase (preferred over `--vault-passphrase` flag) |
850
+
851
+ ---
852
+
853
+ ## Architecture
854
+
855
+ `git-cas` follows hexagonal architecture with four tiers:
856
+
857
+ 1. **Facade** (`index.js`) -- Public entry point. Manages lazy initialization and adaptive crypto.
858
+ 2. **CasService** (`src/domain/services/CasService.js`) -- Lean domain
859
+ facade. Selects store/restore strategies, coordinates injected ports, and
860
+ delegates byte-level work to domain services and strategy entities.
861
+ 3. **VaultService** (`src/domain/services/VaultService.js`) -- Vault use-case
862
+ orchestrator. Delegates Git persistence, parse caching, metadata/tree codecs,
863
+ privacy indexing, key verification, and retry timing to cohesive collaborators.
864
+ 4. **Ports** -- Pure interfaces isolating the domain from I/O: `GitPersistencePort`, `CryptoPort`, `ChunkingPort`, `CompressionPort`, `ObservabilityPort`.
865
+
866
+ Adapters implement ports for specific runtimes: `GitPersistenceAdapter` (shells out to `git` via `@git-stunts/plumbing`), `NodeCryptoAdapter`, `NodeCompressionAdapter`, etc.
867
+
868
+ For the full architecture breakdown, see [ARCHITECTURE.md](./ARCHITECTURE.md).
869
+
870
+ ---
871
+
872
+ **Tests are the spec. Every feature is defined by its tests.**