@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
@@ -0,0 +1,495 @@
1
+ /**
2
+ * Shared reporting helpers for vault diagnostics commands.
3
+ */
4
+ import { ErrorCodes } from '../../src/domain/errors/index.js';
5
+
6
+ const VAULT_METADATA_MISSING_MESSAGE = '.vault.json metadata is missing or invalid';
7
+
8
+ /**
9
+ * @typedef {{ slug: string, treeOid: string, manifest: { toJSON?: () => any } | Record<string, any> }} VaultRecord
10
+ * @typedef {{
11
+ * entries: number,
12
+ * totalLogicalSize: number,
13
+ * totalChunkRefs: number,
14
+ * totalChunkBytes: number,
15
+ * uniqueChunks: number,
16
+ * duplicateChunkRefs: number,
17
+ * uniqueChunkBytes: number,
18
+ * duplicateChunkBytes: number,
19
+ * dedupRatio: number,
20
+ * byteDedupRatio: number,
21
+ * encryptedEntries: number,
22
+ * envelopeEntries: number,
23
+ * compressedEntries: number,
24
+ * chunkingStrategies: Record<string, number>,
25
+ * largestEntry: { slug: string, size: number } | null,
26
+ * }} VaultStats
27
+ * @typedef {{
28
+ * scope: 'vault' | 'entry',
29
+ * code: string,
30
+ * message: string,
31
+ * slug?: string,
32
+ * treeOid?: string,
33
+ * }} DoctorIssue
34
+ * @typedef {{
35
+ * status: 'ok' | 'warn' | 'fail',
36
+ * hasVault: boolean,
37
+ * commitOid: string | null,
38
+ * entryCount: number,
39
+ * checkedEntries: number,
40
+ * validEntries: number,
41
+ * invalidEntries: number,
42
+ * metadataEncrypted: boolean,
43
+ * stats: VaultStats,
44
+ * issues: DoctorIssue[],
45
+ * }} DoctorReport
46
+ */
47
+
48
+ /**
49
+ * Normalize a manifest-like value to plain JSON data.
50
+ *
51
+ * @param {{ toJSON?: () => any } | Record<string, any>} manifest
52
+ * @returns {Record<string, any>}
53
+ */
54
+ function toManifestData(manifest) {
55
+ return typeof manifest?.toJSON === 'function' ? manifest.toJSON() : manifest;
56
+ }
57
+
58
+ /**
59
+ * Format a byte count using binary units.
60
+ *
61
+ * @param {number} bytes
62
+ * @returns {string}
63
+ */
64
+ function formatBytes(bytes) {
65
+ if (!Number.isFinite(bytes) || bytes < 0) {
66
+ return '0 bytes';
67
+ }
68
+ if (bytes < 1024) {
69
+ return `${bytes} bytes`;
70
+ }
71
+
72
+ const units = ['KiB', 'MiB', 'GiB', 'TiB'];
73
+ let value = bytes;
74
+ let unitIndex = -1;
75
+ while (value >= 1024 && unitIndex < units.length - 1) {
76
+ value /= 1024;
77
+ unitIndex += 1;
78
+ }
79
+ return `${value.toFixed(1)} ${units[unitIndex]}`;
80
+ }
81
+
82
+ /**
83
+ * Render aligned key/value pairs with themed labels.
84
+ *
85
+ * @param {Array<[string, string | number]>} pairs
86
+ * @param {{ themeText?: (text: string, opts: { tone: string }) => string }} [opts]
87
+ * @returns {string[]}
88
+ */
89
+ function renderKeyValueLines(pairs, opts) {
90
+ const labelWidth = pairs.reduce((max, [label]) => Math.max(max, label.length), 0);
91
+ const fmt = opts?.themeText;
92
+ return pairs.map(([label, value]) => {
93
+ const key = fmt ? fmt(label.padEnd(labelWidth), { tone: 'accent' }) : label.padEnd(labelWidth);
94
+ return `${key} ${value}`;
95
+ });
96
+ }
97
+
98
+ /**
99
+ * Create an empty stats payload.
100
+ *
101
+ * @returns {VaultStats}
102
+ */
103
+ function emptyVaultStats() {
104
+ return {
105
+ entries: 0,
106
+ totalLogicalSize: 0,
107
+ totalChunkRefs: 0,
108
+ totalChunkBytes: 0,
109
+ uniqueChunks: 0,
110
+ duplicateChunkRefs: 0,
111
+ uniqueChunkBytes: 0,
112
+ duplicateChunkBytes: 0,
113
+ dedupRatio: 1,
114
+ byteDedupRatio: 1,
115
+ encryptedEntries: 0,
116
+ envelopeEntries: 0,
117
+ compressedEntries: 0,
118
+ chunkingStrategies: {},
119
+ largestEntry: null,
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Return true when manifest uses envelope recipients.
125
+ *
126
+ * @param {Record<string, any>} manifest
127
+ * @returns {boolean}
128
+ */
129
+ function hasEnvelopeRecipients(manifest) {
130
+ return Array.isArray(manifest.encryption?.recipients) && manifest.encryption.recipients.length > 0;
131
+ }
132
+
133
+ /**
134
+ * Return true when manifest is encrypted.
135
+ *
136
+ * @param {Record<string, any>} manifest
137
+ * @returns {boolean}
138
+ */
139
+ function isEncryptedManifest(manifest) {
140
+ return Boolean(manifest.encryption?.encrypted || hasEnvelopeRecipients(manifest));
141
+ }
142
+
143
+ /**
144
+ * Extract valid chunk references from a manifest.
145
+ *
146
+ * @param {Record<string, any>} manifest
147
+ * @returns {Array<{ blob: string, size: number }>}
148
+ */
149
+ function listChunkRefs(manifest) {
150
+ const chunks = Array.isArray(manifest.chunks) ? manifest.chunks : [];
151
+ return chunks
152
+ .map((chunk) => ({
153
+ blob: typeof chunk?.blob === 'string' ? chunk.blob : '',
154
+ size: Number.isFinite(chunk?.size) && chunk.size >= 0 ? chunk.size : 0,
155
+ }))
156
+ .filter((chunk) => chunk.blob);
157
+ }
158
+
159
+ /**
160
+ * Summarize a single vault record for aggregation.
161
+ *
162
+ * @param {VaultRecord} record
163
+ * @returns {{
164
+ * slug: string,
165
+ * size: number,
166
+ * strategy: string,
167
+ * chunks: Array<{ blob: string, size: number }>,
168
+ * chunkRefs: number,
169
+ * encrypted: boolean,
170
+ * envelope: boolean,
171
+ * compressed: boolean,
172
+ * }}
173
+ */
174
+ function summarizeRecord(record) {
175
+ const manifest = toManifestData(record.manifest);
176
+ const chunks = Array.isArray(manifest.chunks) ? manifest.chunks : [];
177
+ return {
178
+ slug: record.slug,
179
+ size: Number.isFinite(manifest.size) ? manifest.size : 0,
180
+ strategy: manifest.chunking?.strategy ?? 'fixed',
181
+ chunks: listChunkRefs(manifest),
182
+ chunkRefs: chunks.length,
183
+ encrypted: isEncryptedManifest(manifest),
184
+ envelope: hasEnvelopeRecipients(manifest),
185
+ compressed: Boolean(manifest.compression),
186
+ };
187
+ }
188
+
189
+ /**
190
+ * Merge a summarized record into aggregate stats.
191
+ *
192
+ * @param {VaultStats} stats
193
+ * @param {ReturnType<typeof summarizeRecord>} summary
194
+ * @param {Map<string, number>} uniqueChunks
195
+ * @returns {void}
196
+ */
197
+ function applyRecordSummary(stats, summary, uniqueChunks) {
198
+ stats.entries += 1;
199
+ stats.totalLogicalSize += summary.size;
200
+ stats.totalChunkRefs += summary.chunkRefs;
201
+ stats.totalChunkBytes += summary.chunks.reduce((sum, chunk) => sum + chunk.size, 0);
202
+ if (summary.encrypted) { stats.encryptedEntries += 1; }
203
+ if (summary.envelope) { stats.envelopeEntries += 1; }
204
+ if (summary.compressed) { stats.compressedEntries += 1; }
205
+ stats.chunkingStrategies[summary.strategy] = (stats.chunkingStrategies[summary.strategy] ?? 0) + 1;
206
+
207
+ if (!stats.largestEntry || summary.size > stats.largestEntry.size) {
208
+ stats.largestEntry = { slug: summary.slug, size: summary.size };
209
+ }
210
+
211
+ for (const chunk of summary.chunks) {
212
+ const priorSize = uniqueChunks.get(chunk.blob);
213
+ uniqueChunks.set(chunk.blob, Math.max(priorSize ?? 0, chunk.size));
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Build aggregate vault stats from loaded manifests.
219
+ *
220
+ * Fixed chunking is implicit in current manifests, so missing chunking metadata
221
+ * is treated as `fixed`.
222
+ *
223
+ * @param {VaultRecord[]} records
224
+ * @returns {VaultStats}
225
+ */
226
+ export function buildVaultStats(records) {
227
+ /** @type {VaultStats} */
228
+ const stats = emptyVaultStats();
229
+ const uniqueChunks = new Map();
230
+
231
+ for (const record of records) {
232
+ applyRecordSummary(stats, summarizeRecord(record), uniqueChunks);
233
+ }
234
+
235
+ stats.uniqueChunks = uniqueChunks.size;
236
+ stats.duplicateChunkRefs = Math.max(0, stats.totalChunkRefs - stats.uniqueChunks);
237
+ stats.uniqueChunkBytes = [...uniqueChunks.values()].reduce((sum, size) => sum + size, 0);
238
+ stats.duplicateChunkBytes = Math.max(0, stats.totalChunkBytes - stats.uniqueChunkBytes);
239
+ stats.dedupRatio = stats.uniqueChunks > 0
240
+ ? stats.totalChunkRefs / stats.uniqueChunks
241
+ : 1;
242
+ stats.byteDedupRatio = stats.uniqueChunkBytes > 0
243
+ ? stats.totalChunkBytes / stats.uniqueChunkBytes
244
+ : 1;
245
+
246
+ return stats;
247
+ }
248
+
249
+ /**
250
+ * Render a human-readable vault stats report.
251
+ *
252
+ * @param {VaultStats} stats
253
+ * @returns {string}
254
+ */
255
+ export function renderVaultStats(stats) {
256
+ const chunking = Object.entries(stats.chunkingStrategies)
257
+ .sort(([left], [right]) => left.localeCompare(right))
258
+ .map(([strategy, count]) => `${strategy}:${count}`)
259
+ .join(', ') || '-';
260
+
261
+ const largest = stats.largestEntry
262
+ ? `${stats.largestEntry.slug} (${stats.largestEntry.size} bytes)`
263
+ : '-';
264
+
265
+ return [
266
+ ...renderKeyValueLines([
267
+ ['entries', stats.entries],
268
+ ['logical-size', `${formatBytes(stats.totalLogicalSize)} (${stats.totalLogicalSize} bytes)`],
269
+ ['chunk-bytes', `${formatBytes(stats.totalChunkBytes)} (${stats.totalChunkBytes} bytes)`],
270
+ ['unique-chunk-bytes', `${formatBytes(stats.uniqueChunkBytes)} (${stats.uniqueChunkBytes} bytes)`],
271
+ ['duplicate-chunk-bytes', `${formatBytes(stats.duplicateChunkBytes)} (${stats.duplicateChunkBytes} bytes)`],
272
+ ['chunk-refs', stats.totalChunkRefs],
273
+ ['unique-chunks', stats.uniqueChunks],
274
+ ['duplicate-refs', stats.duplicateChunkRefs],
275
+ ['dedup-ratio', `${stats.dedupRatio.toFixed(2)}x`],
276
+ ['byte-dedup-ratio', `${stats.byteDedupRatio.toFixed(2)}x`],
277
+ ['encrypted', stats.encryptedEntries],
278
+ ['envelope', stats.envelopeEntries],
279
+ ['compressed', stats.compressedEntries],
280
+ ['chunking', chunking],
281
+ ['largest', largest],
282
+ ]),
283
+ '',
284
+ ].join('\n');
285
+ }
286
+
287
+ /**
288
+ * Normalize thrown errors into doctor issue entries.
289
+ *
290
+ * @param {DoctorIssue['scope']} scope
291
+ * @param {unknown} error
292
+ * @param {{ slug?: string, treeOid?: string }} [meta]
293
+ * @returns {DoctorIssue}
294
+ */
295
+ function toDoctorIssue(scope, error, meta = {}) {
296
+ const code = typeof error === 'object' && error && 'code' in error && typeof error.code === 'string'
297
+ ? error.code
298
+ : 'UNKNOWN_ERROR';
299
+ const message = error instanceof Error ? error.message : String(error);
300
+ return { scope, code, message, ...meta };
301
+ }
302
+
303
+ /**
304
+ * Build the failure report for vault-level errors.
305
+ *
306
+ * @param {unknown} error
307
+ * @returns {DoctorReport}
308
+ */
309
+ function buildDoctorFailureReport(error) {
310
+ return {
311
+ status: 'fail',
312
+ hasVault: true,
313
+ commitOid: null,
314
+ entryCount: 0,
315
+ checkedEntries: 0,
316
+ validEntries: 0,
317
+ invalidEntries: 1,
318
+ metadataEncrypted: false,
319
+ stats: emptyVaultStats(),
320
+ issues: [toDoctorIssue('vault', error)],
321
+ };
322
+ }
323
+
324
+ /**
325
+ * Build the report for a missing vault ref.
326
+ *
327
+ * @returns {DoctorReport}
328
+ */
329
+ function buildMissingVaultReport() {
330
+ return {
331
+ status: 'warn',
332
+ hasVault: false,
333
+ commitOid: null,
334
+ entryCount: 0,
335
+ checkedEntries: 0,
336
+ validEntries: 0,
337
+ invalidEntries: 0,
338
+ metadataEncrypted: false,
339
+ stats: emptyVaultStats(),
340
+ issues: [{
341
+ scope: 'vault',
342
+ code: ErrorCodes.VAULT_REF_MISSING,
343
+ message: 'refs/cas/vault not found',
344
+ }],
345
+ };
346
+ }
347
+
348
+ /**
349
+ * Build the failure report for a vault head with missing metadata.
350
+ *
351
+ * @param {{ entries: Map<string, string>, parentCommitOid: string }} state
352
+ * @returns {DoctorReport}
353
+ */
354
+ function buildInvalidVaultMetadataReport(state) {
355
+ return {
356
+ status: 'fail',
357
+ hasVault: true,
358
+ commitOid: state.parentCommitOid,
359
+ entryCount: state.entries.size,
360
+ checkedEntries: 0,
361
+ validEntries: 0,
362
+ invalidEntries: 1,
363
+ metadataEncrypted: false,
364
+ stats: emptyVaultStats(),
365
+ issues: [{
366
+ scope: 'vault',
367
+ code: ErrorCodes.VAULT_METADATA_INVALID,
368
+ message: VAULT_METADATA_MISSING_MESSAGE,
369
+ }],
370
+ };
371
+ }
372
+
373
+ /**
374
+ * Read the current vault state.
375
+ *
376
+ * @param {{ getVaultService: () => Promise<{ readState: (options?: { encryptionKey?: Uint8Array }) => Promise<{ entries: Map<string, string>, parentCommitOid: string | null, metadata: Record<string, any> | null }> }> }} cas
377
+ * @param {{ encryptionKey?: Uint8Array }} [options]
378
+ * @returns {Promise<{ entries: Map<string, string>, parentCommitOid: string | null, metadata: Record<string, any> | null }>}
379
+ */
380
+ async function readVaultState(cas, { encryptionKey } = {}) {
381
+ const vault = await cas.getVaultService();
382
+ return encryptionKey ? await vault.readState({ encryptionKey }) : await vault.readState();
383
+ }
384
+
385
+ /**
386
+ * Load doctor entry records while keeping per-entry failures as issues.
387
+ *
388
+ * @param {{ readManifest: ({ treeOid }: { treeOid: string }) => Promise<any> }} cas
389
+ * @param {Array<{ slug: string, treeOid: string }>} entries
390
+ * @returns {Promise<{ records: VaultRecord[], issues: DoctorIssue[] }>}
391
+ */
392
+ async function readDoctorEntries(cas, entries) {
393
+ /** @type {VaultRecord[]} */
394
+ const records = [];
395
+ /** @type {DoctorIssue[]} */
396
+ const issues = [];
397
+
398
+ for (const entry of entries) {
399
+ try {
400
+ const manifest = await cas.readManifest({ treeOid: entry.treeOid });
401
+ records.push({ ...entry, manifest });
402
+ } catch (error) {
403
+ issues.push(toDoctorIssue('entry', error, entry));
404
+ }
405
+ }
406
+
407
+ return { records, issues };
408
+ }
409
+
410
+ /**
411
+ * Inspect vault health without aborting on per-entry failures.
412
+ *
413
+ * @param {{
414
+ * getVaultService: () => Promise<{ readState: (options?: { encryptionKey?: Uint8Array }) => Promise<{ entries: Map<string, string>, parentCommitOid: string | null, metadata: Record<string, any> | null }> }>,
415
+ * readManifest: ({ treeOid }: { treeOid: string }) => Promise<any>,
416
+ * }} cas
417
+ * @param {{ encryptionKey?: Uint8Array }} [options]
418
+ * @returns {Promise<DoctorReport>}
419
+ */
420
+ export async function inspectVaultHealth(cas, options = {}) {
421
+ let state;
422
+
423
+ try {
424
+ state = await readVaultState(cas, options);
425
+ } catch (error) {
426
+ return buildDoctorFailureReport(error);
427
+ }
428
+
429
+ if (!state.parentCommitOid) {
430
+ return buildMissingVaultReport();
431
+ }
432
+ if (!state.metadata) {
433
+ return buildInvalidVaultMetadataReport(state);
434
+ }
435
+
436
+ const entries = [...state.entries.entries()]
437
+ .map(([slug, treeOid]) => ({ slug, treeOid }))
438
+ .sort((left, right) => left.slug.localeCompare(right.slug));
439
+ const { records, issues } = await readDoctorEntries(cas, entries);
440
+
441
+ return {
442
+ status: issues.length > 0 ? 'fail' : 'ok',
443
+ hasVault: true,
444
+ commitOid: state.parentCommitOid,
445
+ entryCount: entries.length,
446
+ checkedEntries: entries.length,
447
+ validEntries: records.length,
448
+ invalidEntries: issues.length,
449
+ metadataEncrypted: Boolean(state.metadata?.encryption),
450
+ stats: buildVaultStats(records),
451
+ issues,
452
+ };
453
+ }
454
+
455
+ /**
456
+ * Render a human-readable doctor report.
457
+ *
458
+ * @param {DoctorReport} report
459
+ * @returns {string}
460
+ */
461
+ export function renderDoctorReport(report) {
462
+ const lines = [
463
+ ...renderKeyValueLines([
464
+ ['status', report.status],
465
+ ['vault', report.hasVault ? 'present' : 'missing'],
466
+ ['commit', report.commitOid ?? '-'],
467
+ ['entries', report.entryCount],
468
+ ['checked', report.checkedEntries],
469
+ ['valid', report.validEntries],
470
+ ['invalid', report.invalidEntries],
471
+ ['metadata', report.metadataEncrypted ? 'encrypted' : 'plain'],
472
+ ['issues', report.issues.length],
473
+ ['logical-size', `${formatBytes(report.stats.totalLogicalSize)} (${report.stats.totalLogicalSize} bytes)`],
474
+ ['chunk-bytes', `${formatBytes(report.stats.totalChunkBytes)} (${report.stats.totalChunkBytes} bytes)`],
475
+ ['unique-chunk-bytes', `${formatBytes(report.stats.uniqueChunkBytes)} (${report.stats.uniqueChunkBytes} bytes)`],
476
+ ['chunk-refs', report.stats.totalChunkRefs],
477
+ ['unique-chunks', report.stats.uniqueChunks],
478
+ ]),
479
+ '',
480
+ ];
481
+
482
+ if (report.issues.length > 0) {
483
+ lines.push('issue-details');
484
+ for (const issue of report.issues) {
485
+ if (issue.scope === 'entry') {
486
+ lines.push(`[entry] ${issue.slug} (${issue.treeOid}) ${issue.code}: ${issue.message}`);
487
+ } else {
488
+ lines.push(`[vault] ${issue.code}: ${issue.message}`);
489
+ }
490
+ }
491
+ lines.push('');
492
+ }
493
+
494
+ return lines.join('\n');
495
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "sha": "3a3cd3e",
3
+ "timestamp": "2026-05-09T06:59:46.782Z"
4
+ }