@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,266 @@
1
+ import { readPassphraseFile, promptPassphrase } from './ui/passphrase-prompt.js';
2
+
3
+ export const DEFAULT_OS_KEYCHAIN_ACCOUNT = 'git-cas';
4
+
5
+ const INLINE_PASSPHRASE_WARNINGS = Object.freeze({
6
+ vaultPassphrase:
7
+ 'warning: --vault-passphrase exposes secrets through shell history and process listings; prefer --vault-passphrase-file -, GIT_CAS_PASSPHRASE, or --os-keychain-target',
8
+ oldPassphrase:
9
+ 'warning: --old-passphrase exposes secrets through shell history and process listings; prefer --old-passphrase-file -',
10
+ newPassphrase:
11
+ 'warning: --new-passphrase exposes secrets through shell history and process listings; prefer --new-passphrase-file -',
12
+ });
13
+
14
+ /**
15
+ * @param {string} value
16
+ * @returns {string}
17
+ */
18
+ function requireNonEmptyPassphrase(value) {
19
+ if (!value.trim()) {
20
+ throw new Error('Passphrase must not be empty');
21
+ }
22
+ return value;
23
+ }
24
+
25
+ /**
26
+ * @param {string | undefined} value
27
+ * @returns {boolean}
28
+ */
29
+ function hasEnvPassphrase(value) {
30
+ return Boolean(value);
31
+ }
32
+
33
+ /**
34
+ * @param {Record<string, any>} opts
35
+ * @param {(path: string) => Promise<string>} readPassphraseFileFn
36
+ * @returns {Promise<string | undefined>}
37
+ */
38
+ async function resolveFileOrInlinePassphrase(opts, readPassphraseFileFn) {
39
+ if (opts.vaultPassphraseFile !== undefined) {
40
+ return await readPassphraseFileFn(opts.vaultPassphraseFile);
41
+ }
42
+ if (opts.vaultPassphrase !== undefined) {
43
+ return requireNonEmptyPassphrase(opts.vaultPassphrase);
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ /**
49
+ * @param {Record<string, string | undefined>} env
50
+ * @returns {string | undefined}
51
+ */
52
+ function resolveEnvPassphrase(env) {
53
+ if (hasEnvPassphrase(env.GIT_CAS_PASSPHRASE)) {
54
+ return requireNonEmptyPassphrase(env.GIT_CAS_PASSPHRASE);
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * @param {Record<string, any>} opts
61
+ * @param {{
62
+ * readPassphraseFile: (path: string) => Promise<string>,
63
+ * resolveOsKeychainPassphrase: (options: { target: string, account?: string }) => Promise<string>,
64
+ * }} deps
65
+ * @returns {Promise<string | undefined>}
66
+ */
67
+ async function resolveExplicitPassphraseSource(
68
+ opts,
69
+ { readPassphraseFile: readPassphraseFileFn, resolveOsKeychainPassphrase: resolveOsKeychainPassphraseFn }
70
+ ) {
71
+ const fileOrInline = await resolveFileOrInlinePassphrase(opts, readPassphraseFileFn);
72
+ if (fileOrInline !== undefined) {
73
+ return fileOrInline;
74
+ }
75
+ if (opts.osKeychainTarget !== undefined) {
76
+ return await resolveOsKeychainPassphraseFn({
77
+ target: opts.osKeychainTarget,
78
+ account: opts.osKeychainAccount,
79
+ });
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ /**
85
+ * @param {{
86
+ * env?: Record<string, string | undefined>,
87
+ * stdin?: { isTTY?: boolean },
88
+ * readPassphraseFile?: (path: string) => Promise<string>,
89
+ * promptPassphrase?: ({ confirm?: boolean }) => Promise<string>,
90
+ * resolveOsKeychainPassphrase?: (options: { target: string, account?: string }) => Promise<string>,
91
+ * }} deps
92
+ */
93
+ function normalizeResolveDeps(deps) {
94
+ return {
95
+ env: deps.env || process.env,
96
+ stdin: deps.stdin || process.stdin,
97
+ readPassphraseFile: deps.readPassphraseFile || readPassphraseFile,
98
+ promptPassphrase: deps.promptPassphrase || promptPassphrase,
99
+ resolveOsKeychainPassphrase:
100
+ deps.resolveOsKeychainPassphrase || resolveOsKeychainPassphrase,
101
+ };
102
+ }
103
+
104
+ /**
105
+ * @param {{ isTTY?: boolean }} stdin
106
+ * @param {({ confirm?: boolean }) => Promise<string>} promptPassphraseFn
107
+ * @param {{ confirm?: boolean }} extra
108
+ * @returns {Promise<string | undefined>}
109
+ */
110
+ async function resolvePromptPassphrase(stdin, promptPassphraseFn, extra) {
111
+ if (!stdin.isTTY) {
112
+ return undefined;
113
+ }
114
+ return await promptPassphraseFn({ confirm: extra.confirm || false });
115
+ }
116
+
117
+ /**
118
+ * Returns true when a non-interactive passphrase source exists.
119
+ * Does NOT trigger prompts or consume stdin.
120
+ *
121
+ * @param {Record<string, any>} opts
122
+ * @param {Record<string, string | undefined>} [env]
123
+ * @returns {boolean}
124
+ */
125
+ export function hasPassphraseSource(opts, env = process.env) {
126
+ return Boolean(
127
+ opts.vaultPassphraseFile ||
128
+ opts.vaultPassphrase ||
129
+ opts.osKeychainTarget ||
130
+ env.GIT_CAS_PASSPHRASE
131
+ );
132
+ }
133
+
134
+ /**
135
+ * Returns true when an explicit non-interactive passphrase source exists on the CLI.
136
+ * Does not consider ambient environment variables.
137
+ *
138
+ * @param {Record<string, any>} opts
139
+ * @returns {boolean}
140
+ */
141
+ export function hasExplicitPassphraseSource(opts) {
142
+ return (
143
+ opts.vaultPassphraseFile !== undefined ||
144
+ opts.vaultPassphrase !== undefined ||
145
+ opts.osKeychainTarget !== undefined
146
+ );
147
+ }
148
+
149
+ /**
150
+ * Validate human CLI passphrase sources so explicit-but-empty values still count as provided.
151
+ *
152
+ * @param {Record<string, any>} opts
153
+ */
154
+ export function validatePassphraseSources(opts) {
155
+ const explicitSources = [
156
+ opts.vaultPassphrase !== undefined,
157
+ opts.vaultPassphraseFile !== undefined,
158
+ opts.osKeychainTarget !== undefined,
159
+ ].filter(Boolean).length;
160
+
161
+ if (explicitSources > 1) {
162
+ throw new Error(
163
+ 'Provide exactly one vault passphrase source: --vault-passphrase, --vault-passphrase-file, or --os-keychain-target'
164
+ );
165
+ }
166
+ if (opts.osKeychainAccount !== undefined && opts.osKeychainTarget === undefined) {
167
+ throw new Error('Provide --os-keychain-target when using --os-keychain-account');
168
+ }
169
+ if (opts.osKeychainTarget !== undefined && !String(opts.osKeychainTarget).trim()) {
170
+ throw new Error('OS keychain target must not be empty');
171
+ }
172
+ if (opts.osKeychainAccount !== undefined && !String(opts.osKeychainAccount).trim()) {
173
+ throw new Error('OS keychain account must not be empty');
174
+ }
175
+ }
176
+
177
+ /**
178
+ * @param {Record<string, any>} opts
179
+ * @returns {string[]}
180
+ */
181
+ export function inlinePassphraseWarnings(opts) {
182
+ return Object.entries(INLINE_PASSPHRASE_WARNINGS)
183
+ .filter(([key]) => opts[key] !== undefined)
184
+ .map(([, warning]) => warning);
185
+ }
186
+
187
+ /**
188
+ * @param {Record<string, any>} opts
189
+ * @param {(message: string) => void} [write]
190
+ */
191
+ export function warnInlinePassphraseArgs(
192
+ opts,
193
+ write = (message) => process.stderr.write(message)
194
+ ) {
195
+ for (const warning of inlinePassphraseWarnings(opts)) {
196
+ write(`${warning}\n`);
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Resolve a vault passphrase from the OS keychain via @git-stunts/vault.
202
+ *
203
+ * @param {{ target: string, account?: string, importVault?: () => Promise<any> }} options
204
+ * @returns {Promise<string>}
205
+ */
206
+ export async function resolveOsKeychainPassphrase({
207
+ target,
208
+ account = DEFAULT_OS_KEYCHAIN_ACCOUNT,
209
+ importVault = async () => (await import('@git-stunts/vault')).default,
210
+ }) {
211
+ if (!target?.trim()) {
212
+ throw new Error('OS keychain target must not be empty');
213
+ }
214
+ if (!account?.trim()) {
215
+ throw new Error('OS keychain account must not be empty');
216
+ }
217
+
218
+ const Vault = await importVault();
219
+ const vault = new Vault({ account });
220
+ const secret = await vault.getSecret({ target });
221
+
222
+ if (secret === undefined) {
223
+ throw new Error(`OS keychain secret not found for account "${account}" target "${target}"`);
224
+ }
225
+ if (!String(secret).trim()) {
226
+ throw new Error(
227
+ `OS keychain secret for account "${account}" target "${target}" must not be empty`
228
+ );
229
+ }
230
+ return String(secret);
231
+ }
232
+
233
+ /**
234
+ * Resolve passphrase from (in priority order):
235
+ * 1. --vault-passphrase-file <path>
236
+ * 2. --vault-passphrase <pass>
237
+ * 3. --os-keychain-target <target>
238
+ * 4. GIT_CAS_PASSPHRASE env var
239
+ * 5. Interactive TTY prompt (if stdin is a TTY)
240
+ *
241
+ * @param {Record<string, any>} opts
242
+ * @param {{ confirm?: boolean }} [extra]
243
+ * @param {{
244
+ * env?: Record<string, string | undefined>,
245
+ * stdin?: { isTTY?: boolean },
246
+ * readPassphraseFile?: (path: string) => Promise<string>,
247
+ * promptPassphrase?: ({ confirm?: boolean }) => Promise<string>,
248
+ * resolveOsKeychainPassphrase?: (options: { target: string, account?: string }) => Promise<string>,
249
+ * }} [deps]
250
+ * @returns {Promise<string | undefined>}
251
+ */
252
+ export async function resolvePassphrase(opts, extra = {}, deps = {}) {
253
+ const resolvedDeps = normalizeResolveDeps(deps);
254
+ const explicitPassphrase = await resolveExplicitPassphraseSource(opts, {
255
+ readPassphraseFile: resolvedDeps.readPassphraseFile,
256
+ resolveOsKeychainPassphrase: resolvedDeps.resolveOsKeychainPassphrase,
257
+ });
258
+ if (explicitPassphrase !== undefined) {
259
+ return explicitPassphrase;
260
+ }
261
+ const envPassphrase = resolveEnvPassphrase(resolvedDeps.env);
262
+ if (envPassphrase !== undefined) {
263
+ return envPassphrase;
264
+ }
265
+ return await resolvePromptPassphrase(resolvedDeps.stdin, resolvedDeps.promptPassphrase, extra);
266
+ }
@@ -0,0 +1,28 @@
1
+ import path from 'node:path';
2
+ import { createCasError, ErrorCodes } from '../src/domain/errors/index.js';
3
+
4
+ const OUTPUT_PATH_OPTION = 'outputPath';
5
+
6
+ /**
7
+ * Resolves an explicit CLI restore target into the absolute path and authority
8
+ * boundary passed to restoreFile().
9
+ *
10
+ * @param {string} outputPath
11
+ * @param {object} [options]
12
+ * @param {string} [options.cwd]
13
+ * @returns {{ outputPath: string, baseDirectory: string }}
14
+ */
15
+ export function resolveRestoreOutputTarget(outputPath, { cwd = process.cwd() } = {}) {
16
+ if (typeof outputPath !== 'string' || outputPath.trim() === '') {
17
+ throw createCasError(
18
+ 'restore output path must be a non-empty string',
19
+ ErrorCodes.INVALID_OPTIONS,
20
+ { option: OUTPUT_PATH_OPTION },
21
+ );
22
+ }
23
+ const resolvedOutputPath = path.resolve(cwd, outputPath);
24
+ return {
25
+ outputPath: resolvedOutputPath,
26
+ baseDirectory: path.dirname(resolvedOutputPath),
27
+ };
28
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * AssetCard block — structured component for asset metadata display.
3
+ *
4
+ * Takes manifest data and returns a formatted string with badges,
5
+ * key metadata, and consistent layout. Reusable across the dashboard
6
+ * detail pane, CLI inspect, and CLI vault info.
7
+ */
8
+
9
+ import { badge, surfaceToString } from '@flyingrobots/bijou';
10
+ import { hstackSurface } from '@flyingrobots/bijou-tui';
11
+ import { themeText } from '../theme.js';
12
+
13
+ /**
14
+ * @typedef {import('../../../src/domain/value-objects/Manifest.js').ManifestData} ManifestData
15
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
16
+ */
17
+
18
+ /**
19
+ * Format bytes as human-readable string.
20
+ *
21
+ * @param {number} bytes
22
+ * @returns {string}
23
+ */
24
+ function formatBytes(bytes) {
25
+ if (bytes < 1024) {
26
+ return `${bytes} B`;
27
+ }
28
+ if (bytes < 1024 * 1024) {
29
+ return `${(bytes / 1024).toFixed(1)} KiB`;
30
+ }
31
+ if (bytes < 1024 * 1024 * 1024) {
32
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
33
+ }
34
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
35
+ }
36
+
37
+ /**
38
+ * Build status badges for an asset.
39
+ *
40
+ * @param {ManifestData} manifest
41
+ * @param {BijouContext} ctx
42
+ * @returns {import('@flyingrobots/bijou').Surface[]}
43
+ */
44
+ export function buildAssetBadges(manifest, ctx) {
45
+ const badges = [];
46
+ if (Number.isFinite(manifest.version)) {
47
+ badges.push(badge(`v${manifest.version}`, { variant: 'brand', ctx }));
48
+ }
49
+ if (manifest.encryption) {
50
+ badges.push(badge('encrypted', { variant: 'warning', ctx }));
51
+ }
52
+ if (manifest.compression) {
53
+ badges.push(badge(manifest.compression.algorithm, { variant: 'info', ctx }));
54
+ }
55
+ if (manifest.subManifests?.length) {
56
+ badges.push(badge('merkle', { variant: 'accent', ctx }));
57
+ }
58
+ return badges;
59
+ }
60
+
61
+ /**
62
+ * Render the badge row as a string.
63
+ *
64
+ * @param {ManifestData} manifest
65
+ * @param {BijouContext} ctx
66
+ * @returns {string}
67
+ */
68
+ export function renderBadgeRow(manifest, ctx) {
69
+ const badges = buildAssetBadges(manifest, ctx);
70
+ if (badges.length === 0) {
71
+ return '';
72
+ }
73
+ return surfaceToString(hstackSurface(1, ...badges), ctx.style);
74
+ }
75
+
76
+ /**
77
+ * Build a compact asset summary (slug, size, chunk count, crypto status).
78
+ *
79
+ * @param {ManifestData} manifest
80
+ * @param {BijouContext} ctx
81
+ * @returns {string}
82
+ */
83
+ export function renderAssetSummary(manifest, ctx) {
84
+ const crypto = manifest.encryption ? 'encrypted' : 'plaintext';
85
+ const compression = manifest.compression?.algorithm ?? 'none';
86
+ const chunks = manifest.chunks?.length ?? 0;
87
+ const subs = manifest.subManifests?.length ?? 0;
88
+ const lines = [
89
+ `${themeText(ctx, 'slug', { tone: 'accent' })} ${manifest.slug}`,
90
+ `${themeText(ctx, 'size', { tone: 'accent' })} ${formatBytes(manifest.size)}`,
91
+ `${themeText(ctx, 'chunks', { tone: 'accent' })} ${chunks}${subs > 0 ? ` (${subs} sub-manifests)` : ''}`,
92
+ `${themeText(ctx, 'crypto', { tone: 'accent' })} ${crypto}`,
93
+ `${themeText(ctx, 'compress', { tone: 'accent' })} ${compression}`,
94
+ ];
95
+ return lines.join('\n');
96
+ }
97
+
98
+ /**
99
+ * Render a full asset card: badges + summary.
100
+ *
101
+ * @param {ManifestData} manifest
102
+ * @param {BijouContext} ctx
103
+ * @returns {string}
104
+ */
105
+ export function renderAssetCard(manifest, ctx) {
106
+ const badgeRow = renderBadgeRow(manifest, ctx);
107
+ const summary = renderAssetSummary(manifest, ctx);
108
+ return badgeRow ? `${badgeRow}\n\n${summary}` : summary;
109
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * HealthDashboard block — structured doctor report rendering with badges.
3
+ *
4
+ * Takes a pre-computed DoctorReport and returns a formatted string
5
+ * with badge-decorated status, key metrics, and issue details.
6
+ */
7
+
8
+ import { badge, surfaceToString } from '@flyingrobots/bijou';
9
+ import { hstackSurface } from '@flyingrobots/bijou-tui';
10
+ import { themeText } from '../theme.js';
11
+
12
+ /**
13
+ * @typedef {import('../vault-report.js').DoctorReport} DoctorReport
14
+ * @typedef {import('../vault-report.js').DoctorIssue} DoctorIssue
15
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
16
+ */
17
+
18
+ /** @type {Record<string, 'success' | 'warning' | 'danger'>} */
19
+ const STATUS_VARIANTS = {
20
+ ok: 'success',
21
+ warn: 'warning',
22
+ fail: 'danger',
23
+ };
24
+
25
+ /**
26
+ * Format bytes with binary units.
27
+ *
28
+ * @param {number} bytes
29
+ * @returns {string}
30
+ */
31
+ function formatBytes(bytes) {
32
+ if (!Number.isFinite(bytes) || bytes < 0) {
33
+ return '0 bytes';
34
+ }
35
+ if (bytes < 1024) {
36
+ return `${bytes} bytes`;
37
+ }
38
+ const units = ['KiB', 'MiB', 'GiB', 'TiB'];
39
+ let value = bytes;
40
+ let unitIndex = -1;
41
+ while (value >= 1024 && unitIndex < units.length - 1) {
42
+ value /= 1024;
43
+ unitIndex += 1;
44
+ }
45
+ return `${value.toFixed(1)} ${units[unitIndex]}`;
46
+ }
47
+
48
+ /**
49
+ * Render the status badge row.
50
+ *
51
+ * @param {DoctorReport} report
52
+ * @param {BijouContext} ctx
53
+ * @returns {string}
54
+ */
55
+ export function renderHealthStatusRow(report, ctx) {
56
+ const variant = STATUS_VARIANTS[report.status] ?? 'danger';
57
+ const statusBadge = badge(report.status.toUpperCase(), { variant, ctx });
58
+ const vaultBadge = badge(report.hasVault ? 'vault present' : 'no vault', {
59
+ variant: report.hasVault ? 'info' : 'warning',
60
+ ctx,
61
+ });
62
+ const encBadge = badge(report.metadataEncrypted ? 'encrypted' : 'plaintext', {
63
+ variant: report.metadataEncrypted ? 'warning' : 'neutral',
64
+ ctx,
65
+ });
66
+ return surfaceToString(hstackSurface(1, statusBadge, vaultBadge, encBadge), ctx.style);
67
+ }
68
+
69
+ /**
70
+ * Render one aligned metric line.
71
+ *
72
+ * @param {{
73
+ * ctx: BijouContext,
74
+ * label: string,
75
+ * value: string | number,
76
+ * labelWidth: number,
77
+ * }} metric
78
+ * @returns {string}
79
+ */
80
+ function renderMetricLine({ ctx, label, value, labelWidth }) {
81
+ return `${themeText(ctx, label.padEnd(labelWidth), { tone: 'accent' })} ${value}`;
82
+ }
83
+
84
+ /**
85
+ * Render key health metrics.
86
+ *
87
+ * @param {DoctorReport} report
88
+ * @param {BijouContext} ctx
89
+ * @returns {string}
90
+ */
91
+ export function renderHealthMetrics(report, ctx) {
92
+ const pairs = [
93
+ ['entries', report.entryCount],
94
+ ['valid', report.validEntries],
95
+ ['invalid', report.invalidEntries],
96
+ ['logical size', formatBytes(report.stats.totalLogicalSize)],
97
+ ['chunk bytes', formatBytes(report.stats.totalChunkBytes)],
98
+ ['unique chunk bytes', formatBytes(report.stats.uniqueChunkBytes)],
99
+ ['duplicate chunk bytes', formatBytes(report.stats.duplicateChunkBytes)],
100
+ ['chunk refs', report.stats.totalChunkRefs],
101
+ ['unique chunks', report.stats.uniqueChunks],
102
+ ['dedup ratio', `${report.stats.dedupRatio.toFixed(2)}x`],
103
+ ['byte dedup ratio', `${report.stats.byteDedupRatio.toFixed(2)}x`],
104
+ ];
105
+ const labelWidth = pairs.reduce((max, [label]) => Math.max(max, label.length), 0);
106
+ return pairs
107
+ .map(([label, value]) => renderMetricLine({ ctx, label, value, labelWidth }))
108
+ .join('\n');
109
+ }
110
+
111
+ /**
112
+ * Render issue details with severity badges.
113
+ *
114
+ * @param {DoctorIssue[]} issues
115
+ * @param {BijouContext} ctx
116
+ * @returns {string}
117
+ */
118
+ export function renderHealthIssues(issues, ctx) {
119
+ if (issues.length === 0) {
120
+ return '';
121
+ }
122
+ const lines = [themeText(ctx, `Issues (${issues.length})`, { tone: 'danger', bold: true })];
123
+ for (const issue of issues) {
124
+ const scope = issue.scope === 'entry'
125
+ ? `${themeText(ctx, issue.slug ?? '-', { tone: 'primary' })} `
126
+ : '';
127
+ lines.push(` ${scope}${themeText(ctx, issue.code, { tone: 'warning' })}: ${issue.message}`);
128
+ }
129
+ return lines.join('\n');
130
+ }
131
+
132
+ /**
133
+ * Render a full health dashboard: status badges + metrics + issues.
134
+ *
135
+ * @param {DoctorReport} report
136
+ * @param {BijouContext} ctx
137
+ * @returns {string}
138
+ */
139
+ export function renderHealthDashboard(report, ctx) {
140
+ const sections = [
141
+ renderHealthStatusRow(report, ctx),
142
+ renderHealthMetrics(report, ctx),
143
+ ];
144
+ const issues = renderHealthIssues(report.issues, ctx);
145
+ if (issues) {
146
+ sections.push(issues);
147
+ }
148
+ return sections.join('\n\n');
149
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * HeatmapBlock — grid visualization of chunk values with gradient coloring.
3
+ *
4
+ * Accepts an array of cell values and renders a wrapped grid using
5
+ * Surface construction. Handles responsive wrapping based on available
6
+ * width without manual column counting.
7
+ */
8
+
9
+ import { gradientText } from '@flyingrobots/bijou';
10
+
11
+ /** @type {import('@flyingrobots/bijou').GradientStop[]} */
12
+ const DEFAULT_GRADIENT = [
13
+ { pos: 0, color: [0, 255, 255] },
14
+ { pos: 1, color: [255, 0, 255] },
15
+ ];
16
+
17
+ const BLOCK_CHAR = '\u2588';
18
+
19
+ /**
20
+ * @typedef {Object} HeatmapOptions
21
+ * @property {number} width - Available width in columns.
22
+ * @property {number[]} [breaks] - Indices where a line break should be forced (e.g. sub-manifest boundaries).
23
+ * @property {import('@flyingrobots/bijou').GradientStop[]} [gradient] - Custom gradient stops.
24
+ * @property {import('@flyingrobots/bijou').StyleFunction} [style] - Style function for gradient rendering.
25
+ */
26
+
27
+ /**
28
+ * Render a heatmap grid as a gradient-colored string.
29
+ *
30
+ * Each cell is a single block character. Cells wrap at `width` columns.
31
+ * Optional `breaks` array forces line breaks at specific indices
32
+ * (e.g. sub-manifest boundaries).
33
+ *
34
+ * @param {number} cellCount - Number of cells to render.
35
+ * @param {HeatmapOptions} options
36
+ * @returns {string}
37
+ */
38
+ export function renderHeatmapGrid(cellCount, options) {
39
+ const { width, breaks, gradient = DEFAULT_GRADIENT, style } = options;
40
+ const breakSet = breaks ? new Set(breaks) : new Set();
41
+ const gridWidth = Math.max(1, width);
42
+
43
+ const rows = [];
44
+ let row = '';
45
+ let col = 0;
46
+
47
+ for (let i = 0; i < cellCount; i++) {
48
+ if (breakSet.has(i) && col > 0) {
49
+ rows.push(row);
50
+ row = '';
51
+ col = 0;
52
+ }
53
+ row += BLOCK_CHAR;
54
+ col++;
55
+ if (col >= gridWidth) {
56
+ rows.push(row);
57
+ row = '';
58
+ col = 0;
59
+ }
60
+ }
61
+ if (row.length > 0) {
62
+ rows.push(row);
63
+ }
64
+
65
+ const grid = rows.join('\n');
66
+ return gradientText(grid, gradient, { style });
67
+ }