@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
@@ -0,0 +1,514 @@
1
+ # Architecture: `git-cas`
2
+
3
+ This document is the high-level map of the shipped `git-cas` system.
4
+
5
+ It is intentionally not a full API reference. For command and method details,
6
+ see [docs/API.md](./docs/API.md). For crypto and security guidance, see
7
+ [SECURITY.md](./SECURITY.md). For attacker models, trust boundaries, and
8
+ metadata exposure, see [docs/THREAT_MODEL.md](./docs/THREAT_MODEL.md).
9
+
10
+ ## System Model
11
+
12
+ `git-cas` uses Git as the storage substrate, not as a user-facing abstraction.
13
+
14
+ At a high level, the system does four things:
15
+
16
+ 1. turns input bytes into chunk blobs stored in Git
17
+ 2. records how to rebuild those bytes in a manifest
18
+ 3. emits a Git tree that keeps the manifest and chunk blobs reachable
19
+ 4. optionally indexes trees by slug through a GC-safe vault ref
20
+
21
+ The same core supports:
22
+
23
+ - a library facade in [index.js](./index.js)
24
+ - a human CLI and TUI under `bin/`
25
+ - a machine-facing agent CLI under `bin/agent/`
26
+
27
+ Those surfaces are different contracts over one shared core.
28
+
29
+ ## Dependency Direction
30
+
31
+ ```
32
+ Facade (index.js)
33
+ │
34
+ ▼
35
+ Domain (src/domain/)
36
+ │
37
+ ▼
38
+ Ports (src/ports/) ← abstract interfaces only
39
+ ▲
40
+ │
41
+ Infrastructure (src/infrastructure/) ← concrete adapters
42
+ ```
43
+
44
+ Dependencies point inward. Domain depends on ports (abstractions). Infrastructure
45
+ implements those ports but is never imported by the domain. The facade wires
46
+ adapters to ports at construction time.
47
+
48
+ `src/helpers/` contains pure utility functions with no domain or infrastructure
49
+ dependencies. They may be imported by any layer.
50
+
51
+ ## CAS Pipeline
52
+
53
+ ```mermaid
54
+ flowchart TD
55
+ subgraph Ingress["Ingress Surfaces"]
56
+ LIB[index.js Facade]
57
+ CLI[bin/git-cas.js]
58
+ AGENT[bin/agent/cli.js]
59
+ end
60
+ subgraph Engine["CasService (Engine)"]
61
+ CH[Chunker]
62
+ EN[Encryption]
63
+ CM[Compression]
64
+ MF[Manifest Creator]
65
+ end
66
+ subgraph Persistence["Git Persistence (Substrate)"]
67
+ BL[Blobs]
68
+ TR[Trees]
69
+ CMT[Vault Commits]
70
+ end
71
+
72
+ Ingress --> Engine
73
+ Engine --> Persistence
74
+ ```
75
+
76
+ The machine-facing agent entrypoint is intentionally narrow:
77
+ `bin/agent/cli.js` owns command-name resolution, protocol session lifecycle, and
78
+ exit-code mapping. Command behavior lives under `bin/agent/commands/`, while
79
+ shared request parsing helpers live in `bin/agent/input.js`. CLI and agent
80
+ credential resolution share `bin/credentials.js` so raw key files,
81
+ passphrase-derived vault keys, and encrypted restore input requirements stay
82
+ consistent across human and machine command surfaces.
83
+
84
+ ## Store Pipeline
85
+
86
+ ```
87
+ source → compress? → preChunkTransform? (whole/framed) → chunker → postChunkTransform? (convergent) → persistence
88
+ ```
89
+
90
+ Encryption placement depends on the scheme:
91
+
92
+ - **whole/framed** — encrypts _before_ chunking (pre-chunk transform)
93
+ - **convergent** — encrypts _after_ chunking (post-chunk transform), using a
94
+ deterministic per-chunk nonce derived from chunk content
95
+
96
+ ## Restore Pipeline
97
+
98
+ ```
99
+ persistence → verify chunks → postChunkRestore? (convergent) → preChunkRestore? (whole/framed) → decompress? → output
100
+ ```
101
+
102
+ Transforms are unwound in reverse order. Chunk integrity is verified by SHA-256
103
+ digest before any decryption or decompression.
104
+
105
+ ## Layer Model
106
+
107
+ ### Facade (`index.js`)
108
+
109
+ The public entrypoint is [index.js](./index.js).
110
+
111
+ `ContentAddressableStore` is a high-level facade that:
112
+
113
+ - lazily initializes the underlying services
114
+ - selects the appropriate crypto adapter for the current runtime
115
+ - resolves chunking strategy configuration
116
+ - wires persistence, ref, codec, crypto, chunking, compression, and
117
+ observability adapters
118
+ - exposes convenience methods like `storeFile()` and `restoreFile()`
119
+
120
+ The facade is orchestration glue. It is not the storage engine itself.
121
+
122
+ ### Domain (`src/domain/`)
123
+
124
+ #### Services (`src/domain/services/`)
125
+
126
+ - **`CasService`** — primary domain facade. It is now a lean orchestrator that
127
+ wires ports and delegates byte-level behavior to runtime strategy entities.
128
+ It keeps the public store, restore, manifest, inspection, and recipient/key
129
+ API stable while delegating key resolution, chunk I/O, manifest/tree I/O,
130
+ compression, integrity verification, recipient mutation, and store/restore
131
+ strategy execution to dedicated domain classes.
132
+
133
+ - **`VaultService`** — orchestrates GC-safe vault use cases while keeping the
134
+ public vault API stable. It owns initialization, add/update/list/resolve/remove,
135
+ and history-oriented state reads, then delegates vault-head persistence to
136
+ `VaultPersistence`, parse-stable state memoization to `VaultStateCache`, boundary
137
+ formats to `VaultMetadataCodec` and `VaultTreeCodec`, privacy indexing to
138
+ `VaultPrivacyIndex`, vault-key verification to `VaultKeyVerifier`, retry timing
139
+ to `VaultMutationRetryPolicy`, and slug validation to `Slug`.
140
+
141
+ - **`KeyResolver`** — resolves key sources: passphrase-derived keys via KDF,
142
+ envelope recipient DEK wrapping and unwrapping. `CasService` delegates all key
143
+ material resolution through `this.keyResolver`.
144
+
145
+ - **`ConvergentEncryption`** — per-chunk deterministic encryption and
146
+ decryption. Uses content-derived nonces so identical plaintext chunks produce
147
+ identical ciphertext, preserving deduplication across chunked assets.
148
+
149
+ - **`StorePipeline`** — bounded chunk-write coordinator. Owns semaphore-based
150
+ backpressure, in-flight write tracking, ordered manifest entry append, and
151
+ store-phase error metadata.
152
+
153
+ - **`ChunkRepository`** — chunk blob write/read boundary. Owns digest
154
+ verification, per-chunk convergent encryption hooks, read-size enforcement,
155
+ and prefetch-backed chunk iteration. It uses `StorePipeline` for bounded
156
+ chunk write scheduling.
157
+
158
+ - **`CompressionStreams`** — domain compression boundary. Delegates gzip
159
+ compression/decompression to the injected `CompressionPort` and normalizes
160
+ decompression failures into domain errors.
161
+
162
+ - **`ManifestRepository`** — manifest serialization, tree publication, Merkle
163
+ sub-manifest handling, manifest hash verification, and legacy-scheme readback
164
+ boundary.
165
+
166
+ - **`RecipientService`** — envelope recipient add/remove/list/rotation policy.
167
+ It depends on `KeyResolver` for DEK wrapping and unwrapping.
168
+
169
+ - **`IntegrityVerifier`** — verify-only chunk and authentication boundary for
170
+ plaintext, whole, framed, and convergent encrypted manifests.
171
+
172
+ - **`RestorePipeline`** — retained as the earlier extracted strategy
173
+ classifier/dispatcher and covered by tests. New restore byte execution flows
174
+ use runtime strategy entities in `src/domain/strategies/`.
175
+
176
+ - **`ManifestDiff`** — pure function for chunk-level manifest comparison.
177
+ Reports added, removed, and unchanged chunks between two manifests.
178
+
179
+ - **`PrefetchWindow`** — sliding window that drives ordered parallel chunk reads
180
+ during restore, keeping downstream consumers fed without unbounded memory
181
+ growth.
182
+
183
+ - **`Semaphore`** — concurrency limiter used by `StorePipeline` for parallel
184
+ chunk writes during store.
185
+
186
+ - **`rotateVaultPassphrase`** — coordinates vault-wide passphrase rotation
187
+ across all existing entries.
188
+
189
+ #### Value Objects (`src/domain/value-objects/`)
190
+
191
+ - **`Manifest`** — immutable representation of stored asset metadata.
192
+ - **`Chunk`** — immutable representation of one manifest chunk entry.
193
+ - **`Oid`** — immutable Git object identifier value with 40-hex validation.
194
+ - **`Slug`** — immutable vault slug representation. It enforces vault slug
195
+ limits and exposes `.toTreePath()` for the percent-encoded Git tree-entry name
196
+ used by plain vault trees.
197
+ - **`EncryptionMetadata`** — immutable encryption metadata boundary used by
198
+ strategies before crypto-port calls.
199
+ - **`StoreEncryptionConfig`** — immutable store encryption policy resolved from
200
+ public options and key material.
201
+
202
+ #### Encryption (`src/domain/encryption/`)
203
+
204
+ - **`schemes.js`** — single source of truth for encryption scheme identifiers:
205
+ `whole`, `framed`, `convergent`. Legacy scheme identifiers are recognized
206
+ solely to produce actionable migration error messages.
207
+
208
+ #### Schemas (`src/domain/schemas/`)
209
+
210
+ - **`ManifestSchema`** — Zod schemas for manifest and chunk validation. Used by
211
+ the value objects and codec layers.
212
+
213
+ #### Errors (`src/domain/errors/`)
214
+
215
+ - **`CasError`** — structured error type with a stable `code` string and
216
+ arbitrary `metadata` object. All domain errors flow through this type.
217
+
218
+ #### Helpers (`src/domain/helpers/`)
219
+
220
+ - **`buildKdfMetadata`** — assembles KDF parameter metadata for manifest
221
+ storage.
222
+ - **`scryptMaxmem`** — computes the scrypt memory ceiling for the current
223
+ platform.
224
+
225
+ ### Ports (`src/ports/`)
226
+
227
+ Ports define the abstract interfaces the domain depends on. Each port is a class
228
+ with methods that throw "not implemented" by default.
229
+
230
+ - **`CryptoPort`** — SHA-256 hashing, AES-256-GCM encrypt/decrypt, KDF
231
+ (scrypt), HMAC, random bytes, and deterministic encryption for convergent
232
+ mode.
233
+ - **`GitPersistencePort`** — blob read/write, tree read/write, and
234
+ `readBlobStream` for streaming chunk retrieval.
235
+ - **`GitRefPort`** — ref resolution, commit creation, and compare-and-swap ref
236
+ updates.
237
+ - **`ChunkingPort`** — strategy interface for fixed-size and content-defined
238
+ chunking.
239
+ - **`CodecPort`** — manifest serialization and deserialization.
240
+ - **`CompressionPort`** — compress/decompress for both byte arrays and streams.
241
+ - **`ObservabilityPort`** — metrics, logs, and spans without binding the domain
242
+ to any runtime event API.
243
+
244
+ ### Infrastructure (`src/infrastructure/`)
245
+
246
+ #### Adapters (`src/infrastructure/adapters/`)
247
+
248
+ Crypto:
249
+ - **`NodeCryptoAdapter`** — `CryptoPort` backed by `node:crypto`.
250
+ - **`BunCryptoAdapter`** — `CryptoPort` optimized for Bun's native crypto.
251
+ - **`WebCryptoAdapter`** — `CryptoPort` backed by the Web Crypto API (used by
252
+ Deno and other Web Crypto-capable runtimes).
253
+ - **`createCryptoAdapter`** — factory that selects the appropriate crypto
254
+ adapter for the detected runtime.
255
+
256
+ Git:
257
+ - **`GitPersistenceAdapter`** — `GitPersistencePort` implementation using
258
+ `@git-stunts/plumbing` to shell out to the `git` CLI.
259
+ - **`GitRefAdapter`** — `GitRefPort` implementation using
260
+ `@git-stunts/plumbing`.
261
+
262
+ Compression:
263
+ - **`NodeCompressionAdapter`** — `CompressionPort` backed by `node:zlib`.
264
+
265
+ Observability:
266
+ - **`SilentObserver`** — no-op `ObservabilityPort` (default).
267
+ - **`EventEmitterObserver`** — `ObservabilityPort` that emits Node
268
+ `EventEmitter` events.
269
+ - **`StatsCollector`** — `ObservabilityPort` that accumulates operation
270
+ statistics.
271
+
272
+ File I/O:
273
+ - **`FileIOHelper`** — file-backed convenience helpers (`storeFile`,
274
+ `restoreFile`) used by the facade.
275
+
276
+ #### Codecs (`src/infrastructure/codecs/`)
277
+
278
+ - **`JsonCodec`** — `CodecPort` using JSON serialization (default).
279
+ - **`CborCodec`** — `CodecPort` using CBOR serialization.
280
+
281
+ #### Chunkers (`src/infrastructure/chunkers/`)
282
+
283
+ - **`FixedChunker`** — `ChunkingPort` that splits input into fixed-size chunks.
284
+ - **`CdcChunker`** — `ChunkingPort` using content-defined chunking with FastCDC
285
+ normalization.
286
+ - **`resolveChunker`** — factory that constructs a chunker from configuration.
287
+
288
+ #### Git Plumbing (`src/infrastructure/createGitPlumbing.js`)
289
+
290
+ - **`createGitPlumbing`** — creates a configured `@git-stunts/plumbing`
291
+ instance. Used by both `GitPersistenceAdapter` and `GitRefAdapter`.
292
+
293
+ ### Helpers (`src/helpers/`)
294
+
295
+ Pure utility functions with no domain or infrastructure coupling:
296
+
297
+ - **`kdfPolicy.js`** — KDF parameter validation and sensible defaults.
298
+ - **`aesGcmMeta.js`** — AES-GCM metadata validation (IV length, tag length).
299
+ - **`canonicalBase64.js`** — base64 encoding round-trip integrity check.
300
+
301
+ ## Storage Model
302
+
303
+ ### Chunks
304
+
305
+ Stored content is broken into chunks and written as Git blobs.
306
+
307
+ The manifest records the authoritative ordered chunk list, including:
308
+
309
+ - chunk index
310
+ - chunk size
311
+ - SHA-256 digest
312
+ - backing blob OID
313
+
314
+ The manifest, not the tree layout, is the source of truth for reconstruction
315
+ order and repeated chunk occurrences.
316
+
317
+ ### Manifests
318
+
319
+ Manifests are encoded through the configured codec:
320
+
321
+ - JSON by default
322
+ - CBOR when configured
323
+
324
+ Small and medium assets use a single manifest blob.
325
+
326
+ Large assets already use Merkle-style manifests. When chunk count exceeds
327
+ `merkleThreshold`, `createTree()` writes:
328
+
329
+ - a root manifest with `version: 2`
330
+ - an empty top-level `chunks` array
331
+ - `subManifests` references pointing at additional manifest blobs
332
+
333
+ `readManifest()` resolves those sub-manifests transparently and reconstructs the
334
+ flat logical chunk list for callers.
335
+
336
+ Merkle manifests are shipped behavior, not future work.
337
+
338
+ ### Trees
339
+
340
+ `createTree()` emits a Git tree that keeps the asset reachable.
341
+
342
+ For non-Merkle assets the tree contains:
343
+
344
+ - `manifest.<ext>`
345
+ - one blob entry per unique chunk digest, in first-seen order
346
+
347
+ For Merkle assets the tree contains:
348
+
349
+ - `manifest.<ext>`
350
+ - `sub-manifest-<n>.<ext>` blobs
351
+ - one blob entry per unique chunk digest, in first-seen order
352
+
353
+ Chunk blobs are deduplicated at the tree-entry level by digest. The manifest
354
+ still remains authoritative for repeated-chunk order and multiplicity.
355
+
356
+ ### Vault
357
+
358
+ The vault is a GC-safe slug index rooted at `refs/cas/vault`.
359
+ For maintainer-level detail on the collaborators, cache rules, and verifier
360
+ flow, see [docs/VAULT_INTERNALS.md](./docs/VAULT_INTERNALS.md).
361
+
362
+ It is implemented as a commit chain. Each vault commit points to a tree
363
+ containing:
364
+
365
+ - one tree entry per stored slug, mapped to that asset's tree OID
366
+ - `.vault.json` metadata for vault configuration
367
+
368
+ `VaultService` orchestrates:
369
+
370
+ - vault initialization
371
+ - add, update, list, resolve, remove, and history-oriented state reads
372
+ - retrying optimistic vault mutations after compare-and-swap conflicts
373
+
374
+ The durable vault boundary is split into cohesive collaborators:
375
+
376
+ - `VaultPersistence` owns the Git substrate: vault-head resolution, tree/blob
377
+ reads, commit creation, and compare-and-swap updates to `refs/cas/vault`. It is
378
+ stateless and does not cache OIDs.
379
+ - `VaultStateCache` owns tree-OID keyed snapshots, parsed entry memoization,
380
+ defensive `VaultState` copies, privacy entry maps by key identity, and
381
+ verified-key memoization.
382
+ - `VaultMetadataCodec` and `VaultTreeCodec` are pure boundary codecs. They encode
383
+ and decode `.vault.json`, plain slug tree names, privacy tree names, and mktree
384
+ record lines without performing I/O.
385
+ - `VaultPrivacyIndex`, `VaultKeyVerifier`, and `VaultMutationRetryPolicy` own the
386
+ HMAC privacy index, constant-time vault-key verifier checks, and exponential
387
+ backoff with jitter.
388
+
389
+ Vault slugs are validated and normalized with `Slug`. Plain vault trees encode
390
+ slug names through `Slug.toTreePath()`; privacy-enabled vaults keep HMAC tree
391
+ entry names and store the slug mapping inside the encrypted privacy index.
392
+
393
+ Vault metadata can include passphrase-derived encryption configuration and
394
+ related counters, but the vault still fundamentally acts as the durable
395
+ slug-to-tree index for stored assets.
396
+
397
+ ## Runtime Model
398
+
399
+ `git-cas` targets multiple JavaScript runtimes.
400
+
401
+ The core architecture is designed so the domain does not care whether it is
402
+ running on Node, Bun, or a Web Crypto-capable environment. Runtime differences
403
+ are isolated in the infrastructure adapters and selected by the facade or CLI
404
+ bootstrapping code.
405
+
406
+ The core byte contract is `Uint8Array`. Node's `Buffer` may appear inside Node
407
+ adapters because it is a `Uint8Array` subclass, but domain services, ports,
408
+ helpers, chunkers, and codecs do not depend on `Buffer` methods or `node:*`
409
+ imports. `test/unit/docs/platform-boundary.test.js` enforces that boundary.
410
+
411
+ The repo enforces this with a real Node, Bun, and Deno test matrix.
412
+
413
+ ## CasService Decomposition Trajectory
414
+
415
+ The repo has an explicit extraction order for `CasService`. The goal is not to
416
+ erase the service as a public entrypoint; the goal is to reduce internal
417
+ coupling while preserving the public `CasService` facade.
418
+
419
+ ### 1. Store write coordination
420
+
421
+ Extracted in v6:
422
+
423
+ - chunk write scheduling
424
+ - backpressure and in-flight orchestration
425
+ - source-vs-sink store error normalization
426
+ - chunk blob writes and digest verification moved behind `ChunkRepository`
427
+
428
+ Why first:
429
+
430
+ - the tests already isolate this behavior well
431
+ - the seam is mostly runtime-neutral
432
+ - it reduces risk in the highest-churn write path
433
+
434
+ Current boundary:
435
+
436
+ - `StorePipeline` owns scheduling and write-phase metadata.
437
+ - `ChunkRepository` owns chunk I/O and verification.
438
+ - store byte execution lives in `StorePlain`, `StoreConvergent`, `StoreFramed`,
439
+ and `StoreWhole`.
440
+ - `CasService` keeps public store policy and manifest finalization.
441
+
442
+ ### 2. Manifest and tree publication
443
+
444
+ Resolved in v6:
445
+
446
+ - manifest assembly
447
+ - chunk-tree entry construction
448
+ - Merkle sub-manifest publication
449
+ - manifest hash verification
450
+ - legacy manifest scheme mapping
451
+
452
+ Why second:
453
+
454
+ - publication logic is cohesive
455
+ - it is mostly independent of restore semantics
456
+ - it provides a stable seam for future manifest evolution
457
+
458
+ ### 3. Recipient mutation flows
459
+
460
+ Resolved in v6:
461
+
462
+ - recipient add/remove
463
+ - key rotation manifest rewriting
464
+
465
+ Why third:
466
+
467
+ - `KeyResolver` is already separate
468
+ - recipient mutation is a distinct policy surface from byte transport
469
+ - it can move without disturbing the store/restore pipeline
470
+
471
+ ### 4. Restore pipeline extraction
472
+
473
+ Resolved in v6:
474
+
475
+ - restore strategy classification
476
+ - restore handler dispatch
477
+ - chunk read and verify
478
+ - buffered vs streaming restore planning
479
+ - gzip and stream bridging
480
+ - framed vs whole-object decrypt routing
481
+ - convergent, framed, whole, compressed, and plaintext restore byte handlers
482
+
483
+ Current boundary:
484
+
485
+ - `RestoreStrategy` selects runtime strategy entities without a scheme switch in
486
+ `CasService`.
487
+ - `RestoreWhole` preserves whole-object authentication boundaries for buffered
488
+ restore and file publication.
489
+ - `RestoreFramed` owns framed record parsing and authenticated frame streaming.
490
+ - `RestoreConvergent` owns per-chunk convergent decrypt/verify flow.
491
+ - `IntegrityVerifier` owns verify-only authentication checks.
492
+
493
+ ### Non-goals
494
+
495
+ - no public API split away from `CasService`
496
+ - no extraction motivated only by class count
497
+ - no restore-platform refactor hidden inside a decomposition cycle
498
+
499
+ ## Reading This With Other Docs
500
+
501
+ Use this document for the current system shape.
502
+
503
+ Use these docs for adjacent truth:
504
+
505
+ - [README.md](./README.md)
506
+ - positioning, feature overview, and release highlights
507
+ - [docs/API.md](./docs/API.md)
508
+ - library and CLI reference
509
+ - [SECURITY.md](./SECURITY.md)
510
+ - crypto and security guidance
511
+ - [docs/THREAT_MODEL.md](./docs/THREAT_MODEL.md)
512
+ - threat model, assets, and trust boundaries
513
+ - [WORKFLOW.md](https://github.com/git-stunts/git-cas/blob/main/WORKFLOW.md)
514
+ - current planning and delivery model