@git-stunts/git-cas 5.3.1 → 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 (174) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +401 -4
  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 +72 -20
  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 +604 -450
  20. package/bin/io.js +86 -0
  21. package/bin/passphrase-source.js +266 -0
  22. package/bin/restore-output-target.js +28 -0
  23. package/bin/ui/blocks/asset-card.js +109 -0
  24. package/bin/ui/blocks/health-dashboard.js +149 -0
  25. package/bin/ui/blocks/heatmap-block.js +67 -0
  26. package/bin/ui/blocks/merkle-explorer.js +163 -0
  27. package/bin/ui/blocks/operation-feed.js +176 -0
  28. package/bin/ui/blocks/wizard-block.js +168 -0
  29. package/bin/ui/components/short-sha.js +36 -0
  30. package/bin/ui/context.js +56 -1
  31. package/bin/ui/dashboard-cmds.js +1578 -13
  32. package/bin/ui/dashboard-view.js +612 -145
  33. package/bin/ui/dashboard.js +998 -214
  34. package/bin/ui/encryption-card.js +69 -26
  35. package/bin/ui/heatmap.js +26 -54
  36. package/bin/ui/history-timeline.js +51 -19
  37. package/bin/ui/manifest-view.js +115 -60
  38. package/bin/ui/merkle-dag.js +83 -0
  39. package/bin/ui/progress.js +15 -9
  40. package/bin/ui/repo-treemap.js +328 -0
  41. package/bin/ui/shaders/bak-sneppen.js +180 -0
  42. package/bin/ui/shaders/fractal-zoom.js +99 -0
  43. package/bin/ui/shaders/merkle-tree.js +142 -0
  44. package/bin/ui/shaders/organic-flow.js +96 -0
  45. package/bin/ui/shaders/phase-portrait.js +93 -0
  46. package/bin/ui/store-wizard.js +296 -0
  47. package/bin/ui/theme.js +155 -0
  48. package/bin/ui/vault-report.js +495 -0
  49. package/build-info.json +4 -0
  50. package/docs/API.md +2224 -0
  51. package/docs/ENCRYPTION_MODES.md +33 -0
  52. package/docs/EXTENDING.md +174 -0
  53. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  54. package/docs/THREAT_MODEL.md +269 -0
  55. package/docs/VAULT_INTERNALS.md +251 -0
  56. package/docs/WALKTHROUGH.md +1868 -0
  57. package/docs/demo.gif +0 -0
  58. package/docs/releases/v6.0.0.md +104 -0
  59. package/examples/README.md +260 -0
  60. package/index.d.ts +208 -65
  61. package/index.js +163 -54
  62. package/package.json +35 -6
  63. package/scripts/migrate-encryption.js +680 -0
  64. package/src/domain/bytes/ByteLayout.js +96 -0
  65. package/src/domain/encoding/base64.js +91 -0
  66. package/src/domain/encoding/hex.js +14 -0
  67. package/src/domain/encoding/utf8.js +123 -0
  68. package/src/domain/encryption/schemes.js +132 -0
  69. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  70. package/src/domain/errors/CasError.d.ts +28 -0
  71. package/src/domain/errors/CasError.js +43 -6
  72. package/src/domain/errors/Codes.js +54 -0
  73. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  74. package/src/domain/errors/GitError.js +10 -0
  75. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  76. package/src/domain/errors/IntegrityError.js +10 -0
  77. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  78. package/src/domain/errors/InvalidOidError.js +10 -0
  79. package/src/domain/errors/InvalidOptionsError.js +10 -0
  80. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  81. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  82. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  83. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  84. package/src/domain/errors/PortNotImplementedError.js +10 -0
  85. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  86. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  87. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  88. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  89. package/src/domain/errors/createCasError.js +68 -0
  90. package/src/domain/errors/index.js +20 -0
  91. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  92. package/src/domain/helpers/codecBytes.js +34 -0
  93. package/src/domain/helpers/gitRefErrors.js +84 -0
  94. package/src/domain/helpers/scryptMaxmem.js +22 -0
  95. package/src/domain/outcomes/RestoreFailure.js +15 -0
  96. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  97. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  98. package/src/domain/outcomes/StoreFailure.js +15 -0
  99. package/src/domain/outcomes/StoreOutcome.js +11 -0
  100. package/src/domain/outcomes/StoreSuccess.js +17 -0
  101. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  102. package/src/domain/schemas/ManifestSchema.js +67 -13
  103. package/src/domain/services/CasService.d.ts +123 -38
  104. package/src/domain/services/CasService.js +298 -834
  105. package/src/domain/services/ChunkRepository.js +230 -0
  106. package/src/domain/services/CompressionStreams.js +72 -0
  107. package/src/domain/services/ConvergentEncryption.js +128 -0
  108. package/src/domain/services/GitTreeBuilder.js +86 -0
  109. package/src/domain/services/IntegrityVerifier.js +199 -0
  110. package/src/domain/services/KeyResolver.js +49 -42
  111. package/src/domain/services/ManifestDiff.js +56 -0
  112. package/src/domain/services/ManifestRepository.js +286 -0
  113. package/src/domain/services/PrefetchWindow.js +48 -0
  114. package/src/domain/services/RecipientService.js +157 -0
  115. package/src/domain/services/RedactingObservability.js +169 -0
  116. package/src/domain/services/RestorePipeline.js +68 -0
  117. package/src/domain/services/StorePipeline.js +201 -0
  118. package/src/domain/services/VaultKeyVerifier.js +101 -0
  119. package/src/domain/services/VaultMetadataCodec.js +206 -0
  120. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  121. package/src/domain/services/VaultPersistence.js +410 -0
  122. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  123. package/src/domain/services/VaultService.js +749 -251
  124. package/src/domain/services/VaultStateCache.js +225 -0
  125. package/src/domain/services/VaultTreeCodec.js +121 -0
  126. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  127. package/src/domain/strategies/Aad.js +39 -0
  128. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  129. package/src/domain/strategies/RestoreCompressed.js +40 -0
  130. package/src/domain/strategies/RestoreConvergent.js +44 -0
  131. package/src/domain/strategies/RestoreFramed.js +55 -0
  132. package/src/domain/strategies/RestorePlain.js +37 -0
  133. package/src/domain/strategies/RestoreStrategy.js +35 -0
  134. package/src/domain/strategies/RestoreWhole.js +135 -0
  135. package/src/domain/strategies/StoreConvergent.js +28 -0
  136. package/src/domain/strategies/StoreFramed.js +39 -0
  137. package/src/domain/strategies/StorePlain.js +20 -0
  138. package/src/domain/strategies/StoreStrategy.js +61 -0
  139. package/src/domain/strategies/StoreWhole.js +34 -0
  140. package/src/domain/value-objects/Chunk.js +1 -2
  141. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  142. package/src/domain/value-objects/Manifest.d.ts +40 -4
  143. package/src/domain/value-objects/Manifest.js +61 -20
  144. package/src/domain/value-objects/Oid.js +45 -0
  145. package/src/domain/value-objects/Slug.js +124 -0
  146. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  147. package/src/helpers/aesGcmMeta.js +55 -0
  148. package/src/helpers/canonicalBase64.js +1 -0
  149. package/src/helpers/kdfPolicy.js +194 -0
  150. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  151. package/src/infrastructure/adapters/FileIOHelper.js +178 -13
  152. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  153. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  154. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  155. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  156. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  157. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  158. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  159. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  160. package/src/infrastructure/chunkers/resolveChunker.js +3 -1
  161. package/src/infrastructure/codecs/CborCodec.js +3 -3
  162. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  163. package/src/infrastructure/createGitPlumbing.js +22 -0
  164. package/src/package-version.js +1 -0
  165. package/src/ports/ChunkingPort.js +3 -3
  166. package/src/ports/CodecPort.js +4 -4
  167. package/src/ports/CompressionPort.js +57 -0
  168. package/src/ports/CryptoPort.js +138 -50
  169. package/src/ports/GitPersistencePort.js +32 -2
  170. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  171. package/src/ports/GitRefPort.js +1 -1
  172. package/src/types/ambient.d.ts +10 -5
  173. package/test/CONVENTIONS.md +94 -0
  174. package/test/cycles/README.md +13 -0
@@ -2,23 +2,1427 @@
2
2
  * Async command factories for the vault dashboard.
3
3
  */
4
4
 
5
+ import { lstat, readFile, readdir } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { buildVaultStats, inspectVaultHealth } from './vault-report.js';
8
+
5
9
  /** @typedef {import('../../index.js').default} ContentAddressableStore */
10
+ /** @typedef {{ type: 'vault' } | { type: 'ref', ref: string } | { type: 'oid', treeOid: string }} DashSource */
11
+ /** @typedef {{ slug: string, treeOid: string }} ExplorerEntry */
12
+ /** @typedef {'repository' | 'source'} TreemapScope */
13
+ /** @typedef {'tracked' | 'ignored'} TreemapWorktreeMode */
14
+ /** @typedef {'oid' | 'manifest' | 'tree' | 'index' | 'hint' | 'opaque'} RefResolutionKind */
15
+ /** @typedef {'worktree' | 'git' | 'ref' | 'vault' | 'cas' | 'meta'} RepoTreemapKind */
16
+ /** @typedef {{ kind: Exclude<RepoTreemapKind, 'meta'>, segments: string[], label: string }} TreemapPathNode */
17
+ /** @typedef {{ id: string, label: string, kind: RepoTreemapKind, value: number, detail: string, drillable: boolean, path: TreemapPathNode | null }} RepoTreemapTile */
18
+ /** @typedef {{
19
+ * ref: string,
20
+ * oid: string,
21
+ * namespace: string,
22
+ * browsable: boolean,
23
+ * resolution: RefResolutionKind,
24
+ * entryCount: number,
25
+ * detail: string,
26
+ * previewSlugs: string[],
27
+ * source: Extract<DashSource, { type: 'ref' }> | null,
28
+ * }} RefInventoryItem */
29
+ /** @typedef {{
30
+ * namespaces: Array<{ namespace: string, count: number, browsable: number }>,
31
+ * refs: RefInventoryItem[],
32
+ * }} RefInventory */
33
+ /** @typedef {{
34
+ * scope: TreemapScope,
35
+ * worktreeMode: TreemapWorktreeMode,
36
+ * cwd: string,
37
+ * source: DashSource,
38
+ * drillPath: TreemapPathNode[],
39
+ * breadcrumb: string[],
40
+ * totalValue: number,
41
+ * tiles: RepoTreemapTile[],
42
+ * notes: string[],
43
+ * summary: {
44
+ * bare: boolean,
45
+ * gitDir: string,
46
+ * worktreeItems: number,
47
+ * worktreePaths: number,
48
+ * refNamespaces: number,
49
+ * refCount: number,
50
+ * vaultEntries: number,
51
+ * sourceEntries: number,
52
+ * }
53
+ * }} RepoTreemapReport
54
+ */
55
+ /** @typedef {{ segments: string[], value: number, detail: string }} HierarchyRecord */
56
+
57
+ /**
58
+ * Namespace bucket label for a git ref.
59
+ *
60
+ * @param {string} ref
61
+ * @returns {string}
62
+ */
63
+ function refNamespace(ref) {
64
+ const parts = ref.split('/');
65
+ if (parts[0] === 'refs' && parts[1]) {
66
+ return `refs/${parts[1]}`;
67
+ }
68
+ return parts[0] || ref;
69
+ }
70
+
71
+ /**
72
+ * Build the segment layout used by the treemap for a git ref.
73
+ *
74
+ * Root scope groups refs by namespace such as `refs/heads` or `refs/warp`
75
+ * rather than starting with the raw `refs` segment.
76
+ *
77
+ * @param {string} ref
78
+ * @returns {string[]}
79
+ */
80
+ function refSegments(ref) {
81
+ const parts = ref.split('/');
82
+ if (parts[0] === 'refs' && parts[1]) {
83
+ return [`refs/${parts[1]}`, ...parts.slice(2)];
84
+ }
85
+ return parts.filter(Boolean);
86
+ }
87
+
88
+ /**
89
+ * Return the display label for one drill path.
90
+ *
91
+ * @param {TreemapPathNode[]} drillPath
92
+ * @returns {string}
93
+ */
94
+ function drillLabel(drillPath) {
95
+ return drillPath.map((node) => node.label).join(' / ') || 'root';
96
+ }
97
+
98
+ /**
99
+ * Create a stable tile id for one hierarchical segment path.
100
+ *
101
+ * @param {Exclude<RepoTreemapKind, 'meta'>} kind
102
+ * @param {string[]} segments
103
+ * @returns {string}
104
+ */
105
+ function tileId(kind, segments) {
106
+ return `${kind}:${segments.join('\u001f')}`;
107
+ }
108
+
109
+ /**
110
+ * Create one treemap path node from a kind and segment list.
111
+ *
112
+ * @param {Exclude<RepoTreemapKind, 'meta'>} kind
113
+ * @param {string[]} segments
114
+ * @returns {TreemapPathNode}
115
+ */
116
+ function pathNode(kind, segments) {
117
+ return {
118
+ kind,
119
+ segments,
120
+ label: segments[segments.length - 1] ?? '',
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Return true when one segment list is nested under another.
126
+ *
127
+ * @param {string[]} left
128
+ * @param {string[]} right
129
+ * @returns {boolean}
130
+ */
131
+ function segmentsStartWith(left, right) {
132
+ if (right.length > left.length) {
133
+ return false;
134
+ }
135
+ return right.every((segment, index) => left[index] === segment);
136
+ }
137
+
138
+ /**
139
+ * Compact OID label for human-facing rows.
140
+ *
141
+ * @param {string} oid
142
+ * @returns {string}
143
+ */
144
+ function shortOid(oid) {
145
+ return oid.slice(0, 12);
146
+ }
147
+
148
+ /**
149
+ * Build a single-entry source result for direct CAS tree inspection.
150
+ *
151
+ * @param {string} slug
152
+ * @param {string} treeOid
153
+ * @returns {{ entries: ExplorerEntry[], metadata: any }}
154
+ */
155
+ function singleEntrySource(slug, treeOid) {
156
+ return {
157
+ entries: [{ slug, treeOid }],
158
+ metadata: null,
159
+ };
160
+ }
161
+
162
+ /**
163
+ * Describe how a ref resolved into CAS entries.
164
+ *
165
+ * @param {RefResolutionKind} resolution
166
+ * @param {{ entries: ExplorerEntry[], resolvedOid?: string, targetTreeOid?: string | null }} result
167
+ * @returns {string}
168
+ */
169
+ function describeResolution(resolution, result) {
170
+ const entryLabel = `${result.entries.length} CAS entr${result.entries.length === 1 ? 'y' : 'ies'}`;
171
+ const target = shortOid(result.targetTreeOid ?? result.resolvedOid ?? '');
172
+ switch (resolution) {
173
+ case 'manifest':
174
+ return `direct manifest tree ${target}`;
175
+ case 'tree':
176
+ return `commit/tree target ${target}`;
177
+ case 'index':
178
+ return `${entryLabel} from index blob`;
179
+ case 'hint':
180
+ return `manifest hint ${target}`;
181
+ case 'oid':
182
+ return `direct CAS tree ${target}`;
183
+ default:
184
+ return entryLabel;
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Format bytes as a compact human-readable string.
190
+ *
191
+ * @param {number} bytes
192
+ * @returns {string}
193
+ */
194
+ function formatBytes(bytes) {
195
+ if (bytes < 1024) { return `${bytes}B`; }
196
+ if (bytes < 1024 * 1024) { return `${(bytes / 1024).toFixed(1)}K`; }
197
+ if (bytes < 1024 * 1024 * 1024) { return `${(bytes / (1024 * 1024)).toFixed(1)}M`; }
198
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}G`;
199
+ }
200
+
201
+ /**
202
+ * Normalize a manifest into plain data.
203
+ *
204
+ * @param {any} manifest
205
+ * @returns {any}
206
+ */
207
+ function manifestData(manifest) {
208
+ return manifest?.toJSON ? manifest.toJSON() : manifest;
209
+ }
210
+
211
+ /**
212
+ * Resolve the true git-dir path for a non-bare working tree.
213
+ *
214
+ * Supports both regular repositories where `.git` is a directory and worktrees
215
+ * where `.git` is a pointer file containing `gitdir: <path>`.
216
+ *
217
+ * @param {string} repoRoot
218
+ * @returns {Promise<string>}
219
+ */
220
+ async function resolveWorktreeGitDir(repoRoot) {
221
+ const dotGitPath = path.join(repoRoot, '.git');
222
+ try {
223
+ const stat = await lstat(dotGitPath);
224
+ if (stat.isDirectory()) {
225
+ return dotGitPath;
226
+ }
227
+ if (!stat.isFile()) {
228
+ return dotGitPath;
229
+ }
230
+ const raw = await readFile(dotGitPath, 'utf8');
231
+ const match = raw.match(/^\s*gitdir:\s*(.+)\s*$/i);
232
+ return match ? path.resolve(repoRoot, match[1]) : dotGitPath;
233
+ } catch {
234
+ return dotGitPath;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Read the Git repo root and git-dir paths for the current CAS plumbing.
240
+ *
241
+ * @param {{ cwd?: string, execute: ({ args }: { args: string[] }) => Promise<string> }} plumbing
242
+ * @returns {Promise<{ cwd: string, gitDir: string, bare: boolean }>}
243
+ */
244
+ async function resolveRepoInfo(plumbing) {
245
+ const cwd = plumbing.cwd ?? process.cwd();
246
+ const bareRaw = await plumbing.execute({ args: ['rev-parse', '--is-bare-repository'] });
247
+ const bare = bareRaw.trim() === 'true';
248
+ let repoRoot = cwd;
249
+ if (!bare) {
250
+ try {
251
+ repoRoot = (await plumbing.execute({ args: ['rev-parse', '--show-toplevel'] })).trim();
252
+ } catch {
253
+ repoRoot = cwd;
254
+ }
255
+ }
256
+ return {
257
+ cwd: repoRoot,
258
+ gitDir: bare ? repoRoot : await resolveWorktreeGitDir(repoRoot),
259
+ bare,
260
+ };
261
+ }
262
+
263
+ /**
264
+ * Parse null-delimited Git output into raw repo-relative paths.
265
+ *
266
+ * @param {string} output
267
+ * @returns {string[]}
268
+ */
269
+ function parseNullPaths(output) {
270
+ return output.split('\0').filter(Boolean);
271
+ }
272
+
273
+ /**
274
+ * Normalize a repo-relative path and return its top-level label.
275
+ *
276
+ * @param {string} repoPath
277
+ * @returns {string}
278
+ */
279
+ /**
280
+ * Recursively collect file records from the filesystem without following
281
+ * symlinks. Directories contribute their leaf files so the treemap can drill
282
+ * deeper instead of stopping at one opaque directory tile.
283
+ *
284
+ * @param {string} targetPath
285
+ * @param {string[]} segments
286
+ * @returns {Promise<Array<{ segments: string[], value: number }>>}
287
+ */
288
+ async function collectFilesystemRecords(targetPath, segments) {
289
+ let stat;
290
+ try {
291
+ stat = await lstat(targetPath);
292
+ } catch {
293
+ return [];
294
+ }
295
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
296
+ return [{ segments, value: stat.size }];
297
+ }
298
+ let entries;
299
+ try {
300
+ entries = await readdir(targetPath, { withFileTypes: true });
301
+ } catch {
302
+ return [];
303
+ }
304
+ return (await Promise.all(entries.map((entry) =>
305
+ collectFilesystemRecords(path.join(targetPath, entry.name), [...segments, entry.name])))).flat();
306
+ }
307
+
308
+ /**
309
+ * Collect Git-reported worktree records for tracked or ignored mode.
310
+ *
311
+ * Tracked mode stays faithful to `git ls-files`. Ignored mode recursively
312
+ * expands ignored directories so the treemap can drill deeper than the single
313
+ * top-level bucket returned by Git.
314
+ *
315
+ * @param {{
316
+ * plumbing: { execute: ({ args }: { args: string[] }) => Promise<string> },
317
+ * repo: { cwd: string, bare: boolean },
318
+ * worktreeMode: TreemapWorktreeMode,
319
+ * }} options
320
+ * @returns {Promise<{ records: HierarchyRecord[], pathCount: number }>}
321
+ */
322
+ async function collectWorktreeRecords({ plumbing, repo, worktreeMode }) {
323
+ if (repo.bare) {
324
+ return { records: [], pathCount: 0 };
325
+ }
326
+
327
+ const args = worktreeMode === 'ignored'
328
+ ? ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '--no-empty-directory', '-z']
329
+ : ['ls-files', '-z'];
330
+
331
+ let output = '';
332
+ try {
333
+ output = await plumbing.execute({ args });
334
+ } catch {
335
+ return { records: [], pathCount: 0 };
336
+ }
337
+
338
+ const repoPaths = parseNullPaths(output);
339
+ const rawRecords = (await Promise.all(repoPaths.map(async (repoPath) => {
340
+ const normalizedPath = repoPath.replace(/\\/g, '/').replace(/\/+$/, '');
341
+ if (!normalizedPath || normalizedPath === '.git' || normalizedPath.startsWith('.git/')) {
342
+ return [];
343
+ }
344
+
345
+ const fullPath = path.join(repo.cwd, normalizedPath);
346
+ const stat = await lstat(fullPath).catch(() => null);
347
+ if (!stat) {
348
+ return [];
349
+ }
350
+
351
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
352
+ return collectFilesystemRecords(fullPath, normalizedPath.split('/'));
353
+ }
354
+
355
+ return [{ segments: normalizedPath.split('/'), value: stat.size }];
356
+ }))).flat();
357
+
358
+ return {
359
+ records: rawRecords.map((record) => ({
360
+ ...record,
361
+ detail: `1 ${worktreeMode} path · ${formatBytes(record.value)} on disk`,
362
+ })),
363
+ pathCount: repoPaths.length,
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Collect git-dir records so repository treemap drill-down can move from
369
+ * `.git/objects` to packfiles and loose-object fanout directories.
370
+ *
371
+ * @param {{ gitDir: string, bare: boolean }} repo
372
+ * @returns {Promise<HierarchyRecord[]>}
373
+ */
374
+ async function collectGitRecords(repo) {
375
+ let entries;
376
+ try {
377
+ entries = await readdir(repo.gitDir, { withFileTypes: true });
378
+ } catch {
379
+ return [];
380
+ }
381
+
382
+ const rawRecords = (await Promise.all(entries.map(async (entry) => {
383
+ if (entry.name === 'refs') {
384
+ return [];
385
+ }
386
+ const rootLabel = repo.bare ? entry.name : `.git/${entry.name}`;
387
+ return collectFilesystemRecords(path.join(repo.gitDir, entry.name), [rootLabel]);
388
+ }))).flat();
389
+
390
+ return rawRecords.map((record) => ({
391
+ ...record,
392
+ detail: `${formatBytes(record.value)} on disk`,
393
+ }));
394
+ }
395
+
396
+ /**
397
+ * Collect one hierarchy record per ref for repository treemap drill-down.
398
+ *
399
+ * @param {RefInventory} inventory
400
+ * @returns {HierarchyRecord[]}
401
+ */
402
+ function collectRefRecords(inventory) {
403
+ return inventory.refs.map((ref) => ({
404
+ segments: refSegments(ref.ref),
405
+ value: Math.max(1, 4096),
406
+ detail: `${ref.browsable ? 'browsable' : 'opaque'} · ${ref.detail} · ${shortOid(ref.oid)}`,
407
+ }));
408
+ }
409
+
410
+ /**
411
+ * Collect logical source records keyed by slug path.
412
+ *
413
+ * @param {Array<ExplorerEntry & { manifest: any, size: number }>} records
414
+ * @returns {HierarchyRecord[]}
415
+ */
416
+ function collectLogicalRecords(records) {
417
+ return records.map((record) => {
418
+ const data = manifestData(record.manifest);
419
+ const format = data.compression?.algorithm ?? 'raw';
420
+ const crypto = data.encryption ? 'enc' : 'plain';
421
+ return {
422
+ segments: record.slug.split('/').filter(Boolean),
423
+ value: Math.max(1, record.size),
424
+ detail: `${formatBytes(record.size)} logical · ${data.chunks?.length ?? 0} chunks · ${crypto}/${format}`,
425
+ };
426
+ });
427
+ }
428
+
429
+ /**
430
+ * Build one visible hierarchy level from leaf records.
431
+ *
432
+ * @param {HierarchyRecord[]} records
433
+ * @param {{
434
+ * kind: Exclude<RepoTreemapKind, 'meta'>,
435
+ * prefixSegments?: string[],
436
+ * aggregateDetail: (bucket: { segments: string[], records: HierarchyRecord[], value: number }) => string,
437
+ * }} options
438
+ * @returns {RepoTreemapTile[]}
439
+ */
440
+ function buildHierarchyTiles(records, options) {
441
+ const prefixSegments = options.prefixSegments ?? [];
442
+ const buckets = new Map();
443
+
444
+ for (const record of records) {
445
+ if (!segmentsStartWith(record.segments, prefixSegments)) {
446
+ continue;
447
+ }
448
+ if (record.segments.length <= prefixSegments.length) {
449
+ continue;
450
+ }
451
+ const childSegments = [...prefixSegments, record.segments[prefixSegments.length]];
452
+ const key = tileId(options.kind, childSegments);
453
+ const bucket = buckets.get(key) ?? { segments: childSegments, records: [], value: 0 };
454
+ bucket.records.push(record);
455
+ bucket.value += record.value;
456
+ buckets.set(key, bucket);
457
+ }
458
+
459
+ return Array.from(buckets.values())
460
+ .map((bucket) => {
461
+ const leaf = bucket.records.length === 1 && bucket.records[0].segments.length === bucket.segments.length
462
+ ? bucket.records[0]
463
+ : null;
464
+ return {
465
+ id: tileId(options.kind, bucket.segments),
466
+ label: bucket.segments[bucket.segments.length - 1] ?? '',
467
+ kind: options.kind,
468
+ value: Math.max(1, bucket.value),
469
+ detail: leaf ? leaf.detail : options.aggregateDetail(bucket),
470
+ drillable: !leaf,
471
+ path: pathNode(options.kind, bucket.segments),
472
+ };
473
+ })
474
+ .sort((left, right) => right.value - left.value || left.label.localeCompare(right.label));
475
+ }
476
+
477
+ /**
478
+ * Load manifests for explorer entries so logical sizes can be summarized.
479
+ *
480
+ * @param {ContentAddressableStore} cas
481
+ * @param {ExplorerEntry[]} entries
482
+ * @returns {Promise<Array<ExplorerEntry & { manifest: any, size: number }>>}
483
+ */
484
+ async function loadEntryRecords(cas, entries) {
485
+ return Promise.all(entries.map(async (entry) => {
486
+ const manifest = await cas.readManifest({ treeOid: entry.treeOid });
487
+ const data = manifestData(manifest);
488
+ return {
489
+ ...entry,
490
+ manifest,
491
+ size: data.size ?? 0,
492
+ };
493
+ }));
494
+ }
495
+
496
+ /**
497
+ * Collapse low-value tiles into a single "other" bucket so the treemap stays legible.
498
+ *
499
+ * @param {RepoTreemapTile[]} tiles
500
+ * @param {number} limit
501
+ * @returns {RepoTreemapTile[]}
502
+ */
503
+ function compactTiles(tiles, limit = 14) {
504
+ const sorted = [...tiles].sort((left, right) => right.value - left.value || left.label.localeCompare(right.label));
505
+ if (sorted.length <= limit) {
506
+ return sorted;
507
+ }
508
+ const kept = sorted.slice(0, limit - 1);
509
+ const remainder = sorted.slice(limit - 1);
510
+ const otherValue = remainder.reduce((sum, tile) => sum + tile.value, 0);
511
+ kept.push({
512
+ id: 'meta:other',
513
+ label: 'other',
514
+ kind: 'meta',
515
+ value: Math.max(1, otherValue),
516
+ detail: `${remainder.length} smaller regions`,
517
+ drillable: false,
518
+ path: null,
519
+ });
520
+ return kept;
521
+ }
522
+
523
+ /**
524
+ * Aggregate detail line for worktree hierarchy buckets.
525
+ *
526
+ * @param {TreemapWorktreeMode} worktreeMode
527
+ * @param {{ records: HierarchyRecord[], value: number }} bucket
528
+ * @returns {string}
529
+ */
530
+ function worktreeAggregateDetail(worktreeMode, bucket) {
531
+ return `${bucket.records.length} ${worktreeMode} path${bucket.records.length === 1 ? '' : 's'} · ${formatBytes(bucket.value)} on disk`;
532
+ }
533
+
534
+ /**
535
+ * Aggregate detail line for git-dir hierarchy buckets.
536
+ *
537
+ * @param {{ records: HierarchyRecord[], value: number }} bucket
538
+ * @returns {string}
539
+ */
540
+ function gitAggregateDetail(bucket) {
541
+ return `${bucket.records.length} git item${bucket.records.length === 1 ? '' : 's'} · ${formatBytes(bucket.value)} on disk`;
542
+ }
543
+
544
+ /**
545
+ * Aggregate detail line for ref hierarchy buckets.
546
+ *
547
+ * @param {{ records: HierarchyRecord[] }} bucket
548
+ * @returns {string}
549
+ */
550
+ function refAggregateDetail(bucket) {
551
+ return `${bucket.records.length} ref${bucket.records.length === 1 ? '' : 's'}`;
552
+ }
553
+
554
+ /**
555
+ * Aggregate detail line for logical CAS hierarchy buckets.
556
+ *
557
+ * @param {{ records: HierarchyRecord[], value: number }} bucket
558
+ * @returns {string}
559
+ */
560
+ function logicalAggregateDetail(bucket) {
561
+ return `${bucket.records.length} entr${bucket.records.length === 1 ? 'y' : 'ies'} · ${formatBytes(bucket.value)} logical`;
562
+ }
563
+
564
+ /**
565
+ * Build repository-scope notes.
566
+ *
567
+ * @param {{ gitDir: string, bare: boolean }} repo
568
+ * @param {TreemapWorktreeMode} worktreeMode
569
+ * @param {TreemapPathNode[]} drillPath
570
+ * @returns {string[]}
571
+ */
572
+ function buildRepositoryNotes(repo, worktreeMode, drillPath) {
573
+ return [
574
+ drillPath.length > 0
575
+ ? `Drilled into ${drillLabel(drillPath)}. Press - to go up a level.`
576
+ : 'Repository view mixes Git-reported worktree paths, .git on-disk bytes, ref namespaces, and logical CAS region sizes.',
577
+ 'Press r to browse refs and switch the dashboard source to a CAS-backed ref.',
578
+ repo.bare
579
+ ? 'Bare repository: worktree regions are omitted.'
580
+ : `Worktree mode ${worktreeMode} via ${worktreeMode === 'tracked' ? 'git ls-files' : 'git ls-files --others --ignored --exclude-standard'}.`,
581
+ `Git dir ${repo.gitDir}`,
582
+ ];
583
+ }
584
+
585
+ /**
586
+ * Tile kind used for logical source treemap nodes.
587
+ *
588
+ * @param {DashSource} source
589
+ * @returns {'vault' | 'cas'}
590
+ */
591
+ function logicalSourceKind(source) {
592
+ return source.type === 'vault' ? 'vault' : 'cas';
593
+ }
594
+
595
+ /**
596
+ * Human-readable source target used in notes and empty states.
597
+ *
598
+ * @param {DashSource} source
599
+ * @returns {string}
600
+ */
601
+ function sourceTarget(source) {
602
+ if (source.type === 'vault') {
603
+ return 'the vault';
604
+ }
605
+ return source.type === 'ref' ? source.ref : source.treeOid;
606
+ }
607
+
608
+ /**
609
+ * Empty source fallback tile.
610
+ *
611
+ * @returns {RepoTreemapTile}
612
+ */
613
+ function emptySourceTile() {
614
+ return {
615
+ id: 'meta:empty-source',
616
+ label: 'empty source',
617
+ kind: 'meta',
618
+ value: 1,
619
+ detail: 'No CAS entries resolved for this source',
620
+ drillable: false,
621
+ path: null,
622
+ };
623
+ }
624
+
625
+ /**
626
+ * Explanatory note lines for source scope.
627
+ *
628
+ * @param {{ source: DashSource, sourceResult: { entries: ExplorerEntry[] }, drillPath: TreemapPathNode[] }} options
629
+ * @returns {string[]}
630
+ */
631
+ function buildSourceNotes({ source, sourceResult, drillPath }) {
632
+ const firstLine = sourceResult.entries.length === 0
633
+ ? `No CAS entries resolved for ${sourceTarget(source)}. Press r to browse refs or T to return to repository scope.`
634
+ : drillPath.length > 0
635
+ ? `Drilled into ${drillLabel(drillPath)}. Press - to go up a level.`
636
+ : `Loaded ${sourceResult.entries.length} source entr${sourceResult.entries.length === 1 ? 'y' : 'ies'} for ${sourceTarget(source)}.`;
637
+
638
+ return [
639
+ firstLine,
640
+ 'Source view weights tiles by logical manifest size.',
641
+ ];
642
+ }
643
+
644
+ /**
645
+ * Summary block for source scope reports.
646
+ *
647
+ * @param {{
648
+ * repo: { bare: boolean, gitDir: string },
649
+ * source: DashSource,
650
+ * sourceResult: { entries: ExplorerEntry[] },
651
+ * }} options
652
+ * @returns {RepoTreemapReport['summary']}
653
+ */
654
+ function buildSourceSummary({ repo, source, sourceResult }) {
655
+ return {
656
+ bare: repo.bare,
657
+ gitDir: repo.gitDir,
658
+ worktreeItems: 0,
659
+ worktreePaths: 0,
660
+ refNamespaces: 0,
661
+ refCount: 0,
662
+ vaultEntries: source.type === 'vault' ? sourceResult.entries.length : 0,
663
+ sourceEntries: sourceResult.entries.length,
664
+ };
665
+ }
666
+
667
+ /**
668
+ * Build the source-focused treemap report.
669
+ *
670
+ * @param {{
671
+ * repo: { cwd: string, gitDir: string, bare: boolean },
672
+ * source: DashSource,
673
+ * sourceResult: { entries: ExplorerEntry[] },
674
+ * sourceRecords: Array<ExplorerEntry & { manifest: any, size: number }>,
675
+ * drillPath: TreemapPathNode[],
676
+ * }} options
677
+ * @returns {RepoTreemapReport}
678
+ */
679
+ function buildSourceScopeReport({ repo, source, sourceResult, sourceRecords, drillPath }) {
680
+ const logicalKind = logicalSourceKind(source);
681
+ const prefixSegments = drillPath[drillPath.length - 1]?.segments ?? [];
682
+ const sourceTiles = compactTiles(buildHierarchyTiles(collectLogicalRecords(sourceRecords), {
683
+ kind: logicalKind,
684
+ prefixSegments,
685
+ aggregateDetail: logicalAggregateDetail,
686
+ }), drillPath.length > 0 ? 24 : 18);
687
+ const totalValue = sourceTiles.reduce((sum, tile) => sum + tile.value, 0);
688
+ return {
689
+ scope: 'source',
690
+ worktreeMode: 'tracked',
691
+ cwd: repo.cwd,
692
+ source,
693
+ drillPath,
694
+ breadcrumb: ['source', ...drillPath.map((node) => node.label)],
695
+ totalValue,
696
+ tiles: sourceTiles.length > 0 ? sourceTiles : [emptySourceTile()],
697
+ notes: buildSourceNotes({ source, sourceResult, drillPath }),
698
+ summary: buildSourceSummary({ repo, source, sourceResult }),
699
+ };
700
+ }
701
+
702
+ /**
703
+ * Worktree treemap options for one hierarchy level.
704
+ *
705
+ * @param {TreemapWorktreeMode} worktreeMode
706
+ * @param {string[]} [prefixSegments]
707
+ * @returns {{
708
+ * kind: 'worktree',
709
+ * prefixSegments?: string[],
710
+ * aggregateDetail: (bucket: { records: HierarchyRecord[], value: number }) => string,
711
+ * }}
712
+ */
713
+ function worktreeTileOptions(worktreeMode, prefixSegments = []) {
714
+ return {
715
+ kind: 'worktree',
716
+ prefixSegments,
717
+ aggregateDetail: (bucket) => worktreeAggregateDetail(worktreeMode, bucket),
718
+ };
719
+ }
720
+
721
+ /**
722
+ * Repository root tiles across worktree, git, refs, vault, and source data.
723
+ *
724
+ * @param {{
725
+ * worktreeRecords: HierarchyRecord[],
726
+ * gitRecords: HierarchyRecord[],
727
+ * refRecords: HierarchyRecord[],
728
+ * vaultLogicalRecords: HierarchyRecord[],
729
+ * sourceLogicalRecords: HierarchyRecord[],
730
+ * worktreeMode: TreemapWorktreeMode,
731
+ * }} options
732
+ * @returns {RepoTreemapTile[]}
733
+ */
734
+ function buildRepositoryRootTiles(options) {
735
+ return compactTiles([
736
+ ...buildHierarchyTiles(options.worktreeRecords, worktreeTileOptions(options.worktreeMode)),
737
+ ...buildHierarchyTiles(options.gitRecords, {
738
+ kind: 'git',
739
+ aggregateDetail: gitAggregateDetail,
740
+ }),
741
+ ...buildHierarchyTiles(options.refRecords, {
742
+ kind: 'ref',
743
+ aggregateDetail: refAggregateDetail,
744
+ }),
745
+ ...buildHierarchyTiles(options.vaultLogicalRecords, {
746
+ kind: 'vault',
747
+ aggregateDetail: logicalAggregateDetail,
748
+ }),
749
+ ...buildHierarchyTiles(options.sourceLogicalRecords, {
750
+ kind: 'cas',
751
+ aggregateDetail: logicalAggregateDetail,
752
+ }),
753
+ ], 18);
754
+ }
755
+
756
+ /**
757
+ * Drill one repository category deeper based on the selected treemap node.
758
+ *
759
+ * @param {{
760
+ * currentNode: TreemapPathNode,
761
+ * worktreeRecords: HierarchyRecord[],
762
+ * gitRecords: HierarchyRecord[],
763
+ * refRecords: HierarchyRecord[],
764
+ * vaultLogicalRecords: HierarchyRecord[],
765
+ * sourceLogicalRecords: HierarchyRecord[],
766
+ * worktreeMode: TreemapWorktreeMode,
767
+ * }} options
768
+ * @returns {RepoTreemapTile[]}
769
+ */
770
+ function buildRepositoryDrillTiles(options) {
771
+ const tileBuilders = {
772
+ worktree: () => buildHierarchyTiles(options.worktreeRecords, worktreeTileOptions(options.worktreeMode, options.currentNode.segments)),
773
+ git: () => buildHierarchyTiles(options.gitRecords, {
774
+ kind: 'git',
775
+ prefixSegments: options.currentNode.segments,
776
+ aggregateDetail: gitAggregateDetail,
777
+ }),
778
+ ref: () => buildHierarchyTiles(options.refRecords, {
779
+ kind: 'ref',
780
+ prefixSegments: options.currentNode.segments,
781
+ aggregateDetail: refAggregateDetail,
782
+ }),
783
+ vault: () => buildHierarchyTiles(options.vaultLogicalRecords, {
784
+ kind: 'vault',
785
+ prefixSegments: options.currentNode.segments,
786
+ aggregateDetail: logicalAggregateDetail,
787
+ }),
788
+ cas: () => buildHierarchyTiles(options.sourceLogicalRecords, {
789
+ kind: 'cas',
790
+ prefixSegments: options.currentNode.segments,
791
+ aggregateDetail: logicalAggregateDetail,
792
+ }),
793
+ };
794
+
795
+ return compactTiles(tileBuilders[options.currentNode.kind](), 24);
796
+ }
797
+
798
+ /**
799
+ * Summary block for repository scope reports.
800
+ *
801
+ * @param {{
802
+ * repo: { bare: boolean, gitDir: string },
803
+ * worktreeRecords: HierarchyRecord[],
804
+ * worktreePaths: number,
805
+ * refInventory: RefInventory,
806
+ * vaultEntries: number,
807
+ * sourceEntries: number,
808
+ * worktreeMode: TreemapWorktreeMode,
809
+ * }} options
810
+ * @returns {RepoTreemapReport['summary']}
811
+ */
812
+ function buildRepositorySummary(options) {
813
+ return {
814
+ bare: options.repo.bare,
815
+ gitDir: options.repo.gitDir,
816
+ worktreeItems: buildHierarchyTiles(options.worktreeRecords, worktreeTileOptions(options.worktreeMode)).length,
817
+ worktreePaths: options.worktreePaths,
818
+ refNamespaces: options.refInventory.namespaces.length,
819
+ refCount: options.refInventory.refs.length,
820
+ vaultEntries: options.vaultEntries,
821
+ sourceEntries: options.sourceEntries,
822
+ };
823
+ }
824
+
825
+ /**
826
+ * Data inputs needed to build repository treemap tiles.
827
+ *
828
+ * @param {{
829
+ * cas: ContentAddressableStore,
830
+ * source: DashSource,
831
+ * repo: { cwd: string, gitDir: string, bare: boolean },
832
+ * plumbing: { execute: ({ args }: { args: string[] }) => Promise<string> },
833
+ * sourceResult: { entries: ExplorerEntry[] },
834
+ * sourceRecords: Array<ExplorerEntry & { manifest: any, size: number }>,
835
+ * worktreeMode: TreemapWorktreeMode,
836
+ * }} options
837
+ * @returns {Promise<{
838
+ * worktreeRecords: HierarchyRecord[],
839
+ * worktreePaths: number,
840
+ * gitRecords: HierarchyRecord[],
841
+ * refInventory: RefInventory,
842
+ * refRecords: HierarchyRecord[],
843
+ * vaultResult: { entries: ExplorerEntry[] },
844
+ * vaultLogicalRecords: HierarchyRecord[],
845
+ * sourceLogicalRecords: HierarchyRecord[],
846
+ * }>}
847
+ */
848
+ async function loadRepositoryScopeData({ cas, source, repo, plumbing, sourceResult, sourceRecords, worktreeMode }) {
849
+ const [{ records: worktreeRecords, pathCount: worktreePaths }, gitRecords, refInventory] = await Promise.all([
850
+ collectWorktreeRecords({ plumbing, repo, worktreeMode }),
851
+ collectGitRecords(repo),
852
+ readRefInventory(cas),
853
+ ]);
854
+ const refRecords = collectRefRecords(refInventory);
855
+ const vaultResult = source.type === 'vault' ? sourceResult : await readSourceEntries(cas, { type: 'vault' });
856
+ const vaultRecords = source.type === 'vault' ? sourceRecords : await loadEntryRecords(cas, vaultResult.entries);
857
+
858
+ return {
859
+ worktreeRecords,
860
+ worktreePaths,
861
+ gitRecords,
862
+ refInventory,
863
+ refRecords,
864
+ vaultResult,
865
+ vaultLogicalRecords: collectLogicalRecords(vaultRecords),
866
+ sourceLogicalRecords: source.type === 'vault' ? [] : collectLogicalRecords(sourceRecords),
867
+ };
868
+ }
869
+
870
+ /**
871
+ * Empty repository fallback tile.
872
+ *
873
+ * @returns {RepoTreemapTile[]}
874
+ */
875
+ function emptyRepositoryTiles() {
876
+ return [{
877
+ id: 'meta:empty-repo',
878
+ label: 'empty repo',
879
+ kind: 'meta',
880
+ value: 1,
881
+ detail: 'No worktree, ref, or CAS regions were detected',
882
+ drillable: false,
883
+ path: null,
884
+ }];
885
+ }
886
+
887
+ /**
888
+ * Final repository-scope report object.
889
+ *
890
+ * @param {{
891
+ * repo: { cwd: string, gitDir: string, bare: boolean },
892
+ * source: DashSource,
893
+ * worktreeMode: TreemapWorktreeMode,
894
+ * drillPath: TreemapPathNode[],
895
+ * tiles: RepoTreemapTile[],
896
+ * worktreeRecords: HierarchyRecord[],
897
+ * worktreePaths: number,
898
+ * refInventory: RefInventory,
899
+ * vaultEntries: number,
900
+ * sourceEntries: number,
901
+ * }} options
902
+ * @returns {RepoTreemapReport}
903
+ */
904
+ function repositoryScopeReport(options) {
905
+ return {
906
+ scope: 'repository',
907
+ worktreeMode: options.worktreeMode,
908
+ cwd: options.repo.cwd,
909
+ source: options.source,
910
+ drillPath: options.drillPath,
911
+ breadcrumb: ['repository', ...options.drillPath.map((node) => node.label)],
912
+ totalValue: options.tiles.reduce((sum, tile) => sum + tile.value, 0),
913
+ tiles: options.tiles.length > 0 ? options.tiles : emptyRepositoryTiles(),
914
+ notes: buildRepositoryNotes(options.repo, options.worktreeMode, options.drillPath),
915
+ summary: buildRepositorySummary({
916
+ repo: options.repo,
917
+ worktreeRecords: options.worktreeRecords,
918
+ worktreePaths: options.worktreePaths,
919
+ refInventory: options.refInventory,
920
+ vaultEntries: options.vaultEntries,
921
+ sourceEntries: options.sourceEntries,
922
+ worktreeMode: options.worktreeMode,
923
+ }),
924
+ };
925
+ }
926
+
927
+ /**
928
+ * Visible tiles for the current repository drill level.
929
+ *
930
+ * @param {{
931
+ * drillPath: TreemapPathNode[],
932
+ * worktreeRecords: HierarchyRecord[],
933
+ * gitRecords: HierarchyRecord[],
934
+ * refRecords: HierarchyRecord[],
935
+ * vaultLogicalRecords: HierarchyRecord[],
936
+ * sourceLogicalRecords: HierarchyRecord[],
937
+ * worktreeMode: TreemapWorktreeMode,
938
+ * }} options
939
+ * @returns {RepoTreemapTile[]}
940
+ */
941
+ function repositoryTilesForDrillPath(options) {
942
+ const currentNode = options.drillPath[options.drillPath.length - 1] ?? null;
943
+ return currentNode
944
+ ? buildRepositoryDrillTiles({
945
+ currentNode,
946
+ worktreeRecords: options.worktreeRecords,
947
+ gitRecords: options.gitRecords,
948
+ refRecords: options.refRecords,
949
+ vaultLogicalRecords: options.vaultLogicalRecords,
950
+ sourceLogicalRecords: options.sourceLogicalRecords,
951
+ worktreeMode: options.worktreeMode,
952
+ })
953
+ : buildRepositoryRootTiles({
954
+ worktreeRecords: options.worktreeRecords,
955
+ gitRecords: options.gitRecords,
956
+ refRecords: options.refRecords,
957
+ vaultLogicalRecords: options.vaultLogicalRecords,
958
+ sourceLogicalRecords: options.sourceLogicalRecords,
959
+ worktreeMode: options.worktreeMode,
960
+ });
961
+ }
962
+
963
+ /**
964
+ * Build repository-scope physical and logical tiles.
965
+ *
966
+ * @param {{
967
+ * cas: ContentAddressableStore,
968
+ * source: DashSource,
969
+ * repo: { cwd: string, gitDir: string, bare: boolean },
970
+ * plumbing: { execute: ({ args }: { args: string[] }) => Promise<string> },
971
+ * sourceResult: { entries: ExplorerEntry[] },
972
+ * sourceRecords: Array<ExplorerEntry & { manifest: any, size: number }>,
973
+ * worktreeMode: TreemapWorktreeMode,
974
+ * drillPath: TreemapPathNode[],
975
+ * }} options
976
+ * @returns {Promise<RepoTreemapReport>}
977
+ */
978
+ async function buildRepositoryScopeReport({ cas, source, repo, plumbing, sourceResult, sourceRecords, worktreeMode, drillPath }) {
979
+ const {
980
+ worktreeRecords,
981
+ worktreePaths,
982
+ gitRecords,
983
+ refInventory,
984
+ refRecords,
985
+ vaultResult,
986
+ vaultLogicalRecords,
987
+ sourceLogicalRecords,
988
+ } = await loadRepositoryScopeData({
989
+ cas,
990
+ source,
991
+ repo,
992
+ plumbing,
993
+ sourceResult,
994
+ sourceRecords,
995
+ worktreeMode,
996
+ });
997
+ const tiles = repositoryTilesForDrillPath({
998
+ drillPath,
999
+ worktreeRecords,
1000
+ gitRecords,
1001
+ refRecords,
1002
+ vaultLogicalRecords,
1003
+ sourceLogicalRecords,
1004
+ worktreeMode,
1005
+ });
1006
+ return repositoryScopeReport({
1007
+ repo,
1008
+ source,
1009
+ worktreeMode,
1010
+ drillPath,
1011
+ tiles,
1012
+ worktreeRecords,
1013
+ worktreePaths,
1014
+ refInventory,
1015
+ vaultEntries: vaultResult.entries.length,
1016
+ sourceEntries: sourceResult.entries.length,
1017
+ });
1018
+ }
1019
+
1020
+ /**
1021
+ * Convert one `show-ref` line into a browsable or opaque ref record.
1022
+ *
1023
+ * @param {ContentAddressableStore} cas
1024
+ * @param {{ service: { persistence: any }, vault: { ref: any } }} ports
1025
+ * @param {string} line
1026
+ * @returns {Promise<RefInventoryItem>}
1027
+ */
1028
+ async function classifyRefLine(cas, ports, line) {
1029
+ const [oid = '', ref = ''] = line.split(' ');
1030
+ try {
1031
+ const result = await resolveSourceDetailed(cas, { type: 'ref', ref }, ports);
1032
+ return {
1033
+ ref,
1034
+ oid,
1035
+ namespace: refNamespace(ref),
1036
+ browsable: true,
1037
+ resolution: result.resolution,
1038
+ entryCount: result.entries.length,
1039
+ detail: describeResolution(result.resolution, result),
1040
+ previewSlugs: result.entries.slice(0, 3).map((entry) => entry.slug),
1041
+ source: { type: 'ref', ref },
1042
+ };
1043
+ } catch (error) {
1044
+ return {
1045
+ ref,
1046
+ oid,
1047
+ namespace: refNamespace(ref),
1048
+ browsable: false,
1049
+ resolution: 'opaque',
1050
+ entryCount: 0,
1051
+ detail: error instanceof Error ? error.message : String(error),
1052
+ previewSlugs: [],
1053
+ source: null,
1054
+ };
1055
+ }
1056
+ }
1057
+
1058
+ /**
1059
+ * Summarize per-namespace ref counts.
1060
+ *
1061
+ * @param {RefInventoryItem[]} refs
1062
+ * @returns {Array<{ namespace: string, count: number, browsable: number }>}
1063
+ */
1064
+ function summarizeRefNamespaces(refs) {
1065
+ const namespaceMap = new Map();
1066
+ for (const ref of refs) {
1067
+ const bucket = namespaceMap.get(ref.namespace) ?? { namespace: ref.namespace, count: 0, browsable: 0 };
1068
+ bucket.count += 1;
1069
+ bucket.browsable += ref.browsable ? 1 : 0;
1070
+ namespaceMap.set(ref.namespace, bucket);
1071
+ }
1072
+ return Array.from(namespaceMap.values()).sort((left, right) => right.count - left.count || left.namespace.localeCompare(right.namespace));
1073
+ }
1074
+
1075
+ /**
1076
+ * Return true when the provided tree OID resolves to a CAS manifest.
1077
+ *
1078
+ * @param {ContentAddressableStore} cas
1079
+ * @param {string} treeOid
1080
+ * @returns {Promise<boolean>}
1081
+ */
1082
+ async function canReadManifest(cas, treeOid) {
1083
+ try {
1084
+ await cas.readManifest({ treeOid });
1085
+ return true;
1086
+ } catch {
1087
+ return false;
1088
+ }
1089
+ }
1090
+
1091
+ /**
1092
+ * Try to resolve a commit/tree-ish object into a tree OID.
1093
+ *
1094
+ * @param {{ resolveTree: (commitOid: string) => Promise<string> }} refPort
1095
+ * @param {string} oid
1096
+ * @returns {Promise<string | null>}
1097
+ */
1098
+ async function tryResolveTree(refPort, oid) {
1099
+ try {
1100
+ return await refPort.resolveTree(oid);
1101
+ } catch {
1102
+ return null;
1103
+ }
1104
+ }
1105
+
1106
+ /**
1107
+ * Read and parse a JSON blob by object ID.
1108
+ *
1109
+ * @param {{ readBlob: (oid: string) => Promise<Buffer> }} persistence
1110
+ * @param {string} oid
1111
+ * @returns {Promise<any | null>}
1112
+ */
1113
+ async function tryReadJsonBlob(persistence, oid) {
1114
+ try {
1115
+ const blob = await persistence.readBlob(oid);
1116
+ return JSON.parse(blob.toString('utf8'));
1117
+ } catch {
1118
+ return null;
1119
+ }
1120
+ }
1121
+
1122
+ /**
1123
+ * Normalize a JSON entry into explorer rows.
1124
+ *
1125
+ * @param {unknown} value
1126
+ * @param {string} fallbackSlug
1127
+ * @returns {ExplorerEntry | null}
1128
+ */
1129
+ function toIndexedEntry(value, fallbackSlug) {
1130
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1131
+ return null;
1132
+ }
1133
+ const record = /** @type {Record<string, any>} */ (value);
1134
+ if (typeof record.treeOid !== 'string') {
1135
+ return null;
1136
+ }
1137
+ return {
1138
+ slug: typeof record.slug === 'string'
1139
+ ? record.slug
1140
+ : typeof record.key === 'string'
1141
+ ? record.key
1142
+ : typeof record.id === 'string'
1143
+ ? record.id
1144
+ : fallbackSlug,
1145
+ treeOid: record.treeOid,
1146
+ };
1147
+ }
1148
+
1149
+ /**
1150
+ * Extract CAS tree references from common JSON index shapes.
1151
+ *
1152
+ * Supports:
1153
+ * - `{ treeOid }`
1154
+ * - `{ entries: { key: { treeOid } } }`
1155
+ * - `{ entries: [{ treeOid, slug? | key? | id? }] }`
1156
+ * - `[{ treeOid, ... }]`
1157
+ *
1158
+ * @param {unknown} json
1159
+ * @param {string} label
1160
+ * @returns {ExplorerEntry[]}
1161
+ */
1162
+ function extractJsonEntries(json, label) {
1163
+ const entries = [];
1164
+
1165
+ const direct = toIndexedEntry(json, label);
1166
+ if (direct) {
1167
+ entries.push(direct);
1168
+ }
1169
+
1170
+ if (Array.isArray(json)) {
1171
+ return json
1172
+ .map((item, index) => toIndexedEntry(item, `${label}#${index + 1}`))
1173
+ .filter(Boolean)
1174
+ .sort((left, right) => left.slug.localeCompare(right.slug));
1175
+ }
1176
+
1177
+ if (!json || typeof json !== 'object') {
1178
+ return entries;
1179
+ }
1180
+
1181
+ const record = /** @type {Record<string, any>} */ (json);
1182
+ if (Array.isArray(record.entries)) {
1183
+ return record.entries
1184
+ .map((item, index) => toIndexedEntry(item, `${label}#${index + 1}`))
1185
+ .filter(Boolean)
1186
+ .sort((left, right) => left.slug.localeCompare(right.slug));
1187
+ }
1188
+
1189
+ if (record.entries && typeof record.entries === 'object' && !Array.isArray(record.entries)) {
1190
+ return Object.entries(record.entries)
1191
+ .map(([key, value]) => toIndexedEntry(value, key))
1192
+ .filter(Boolean)
1193
+ .sort((left, right) => left.slug.localeCompare(right.slug));
1194
+ }
1195
+
1196
+ return entries;
1197
+ }
1198
+
1199
+ /**
1200
+ * Parse a manifest tree hint out of a commit message.
1201
+ *
1202
+ * @param {{ plumbing?: { execute: ({ args }: { args: string[] }) => Promise<string> } }} persistence
1203
+ * @param {string} oid
1204
+ * @returns {Promise<string | null>}
1205
+ */
1206
+ async function tryReadManifestHint(persistence, oid) {
1207
+ if (!persistence.plumbing || typeof persistence.plumbing.execute !== 'function') {
1208
+ return null;
1209
+ }
1210
+ try {
1211
+ const message = await persistence.plumbing.execute({
1212
+ args: ['show', '-s', '--format=%B', oid],
1213
+ });
1214
+ const match = message.match(/^\s*manifest:\s*([0-9a-f]{7,64})\s*$/mi);
1215
+ return match ? match[1] : null;
1216
+ } catch {
1217
+ return null;
1218
+ }
1219
+ }
1220
+
1221
+ /**
1222
+ * Resolve a direct OID source.
1223
+ *
1224
+ * @param {Extract<DashSource, { type: 'oid' }>} source
1225
+ * @returns {{ entries: ExplorerEntry[], metadata: any, resolution: RefResolutionKind, targetTreeOid: string }}
1226
+ */
1227
+ function resolveOidSourceDetailed(source) {
1228
+ return {
1229
+ ...singleEntrySource(`oid:${shortOid(source.treeOid)}`, source.treeOid),
1230
+ resolution: 'oid',
1231
+ targetTreeOid: source.treeOid,
1232
+ };
1233
+ }
1234
+
1235
+ /**
1236
+ * Resolve a ref source into CAS entries.
1237
+ *
1238
+ * @param {ContentAddressableStore} cas
1239
+ * @param {Extract<DashSource, { type: 'ref' }>} source
1240
+ * @param {{ service: { persistence: any }, vault: { ref: any } }} ports
1241
+ * @returns {Promise<{ entries: ExplorerEntry[], metadata: any, resolution: RefResolutionKind, resolvedOid: string, targetTreeOid?: string | null }>}
1242
+ */
1243
+ async function resolveRefSourceDetailed(cas, source, ports) {
1244
+ const { service, vault } = ports;
1245
+ const resolvedOid = await vault.ref.resolveRef(source.ref);
1246
+
1247
+ if (await canReadManifest(cas, resolvedOid)) {
1248
+ return {
1249
+ ...singleEntrySource(source.ref, resolvedOid),
1250
+ resolution: 'manifest',
1251
+ resolvedOid,
1252
+ targetTreeOid: resolvedOid,
1253
+ };
1254
+ }
1255
+
1256
+ const treeOid = await tryResolveTree(vault.ref, resolvedOid);
1257
+ if (treeOid && await canReadManifest(cas, treeOid)) {
1258
+ return {
1259
+ ...singleEntrySource(`${source.ref}^{tree}`, treeOid),
1260
+ resolution: 'tree',
1261
+ resolvedOid,
1262
+ targetTreeOid: treeOid,
1263
+ };
1264
+ }
1265
+
1266
+ const indexed = extractJsonEntries(await tryReadJsonBlob(service.persistence, resolvedOid), source.ref);
1267
+ if (indexed.length > 0) {
1268
+ return {
1269
+ entries: indexed,
1270
+ metadata: null,
1271
+ resolution: 'index',
1272
+ resolvedOid,
1273
+ targetTreeOid: null,
1274
+ };
1275
+ }
1276
+
1277
+ const hintedTreeOid = await tryReadManifestHint(service.persistence, resolvedOid);
1278
+ if (hintedTreeOid) {
1279
+ return {
1280
+ ...singleEntrySource(source.ref, hintedTreeOid),
1281
+ resolution: 'hint',
1282
+ resolvedOid,
1283
+ targetTreeOid: hintedTreeOid,
1284
+ };
1285
+ }
1286
+
1287
+ throw new Error(`Ref ${source.ref} did not resolve to a vault, CAS tree, supported CAS index, or manifest hint`);
1288
+ }
1289
+
1290
+ /**
1291
+ * Resolve dashboard entries for a source and include metadata about how the
1292
+ * source was derived.
1293
+ *
1294
+ * @param {ContentAddressableStore} cas
1295
+ * @param {DashSource} source
1296
+ * @param {{ service?: any, vault?: any }} [ports]
1297
+ * @returns {Promise<{ entries: ExplorerEntry[], metadata: any, resolution: RefResolutionKind, resolvedOid?: string, targetTreeOid?: string | null }>}
1298
+ */
1299
+ async function resolveSourceDetailed(cas, source, ports = {}) {
1300
+ if (source.type === 'oid') {
1301
+ return resolveOidSourceDetailed(source);
1302
+ }
1303
+
1304
+ const service = ports.service ?? await cas.getService();
1305
+ const vault = ports.vault ?? await cas.getVaultService();
1306
+ return resolveRefSourceDetailed(cas, source, { service, vault });
1307
+ }
1308
+
1309
+ /**
1310
+ * Resolve dashboard entries for a non-vault source.
1311
+ *
1312
+ * @param {ContentAddressableStore} cas
1313
+ * @param {{ type: 'ref', ref: string } | { type: 'oid', treeOid: string }} source
1314
+ * @returns {Promise<{ entries: ExplorerEntry[], metadata: any }>}
1315
+ */
1316
+ async function resolveNonVaultSource(cas, source) {
1317
+ const result = await resolveSourceDetailed(cas, source);
1318
+ return { entries: result.entries, metadata: result.metadata };
1319
+ }
1320
+
1321
+ /**
1322
+ * Resolve dashboard entries for the requested source.
1323
+ *
1324
+ * @param {ContentAddressableStore} cas
1325
+ * @param {DashSource} source
1326
+ * @returns {Promise<{ entries: ExplorerEntry[], metadata: any }>}
1327
+ */
1328
+ export async function readSourceEntries(cas, source = { type: 'vault' }) {
1329
+ if (source.type === 'vault') {
1330
+ const [entries, metadata] = await Promise.all([
1331
+ cas.listVault(),
1332
+ cas.getVaultMetadata(),
1333
+ ]);
1334
+ return { entries, metadata };
1335
+ }
1336
+ return resolveNonVaultSource(cas, source);
1337
+ }
1338
+
1339
+ /**
1340
+ * Read and classify refs so the dashboard can browse namespaces and switch the
1341
+ * active source to CAS-backed refs.
1342
+ *
1343
+ * @param {ContentAddressableStore} cas
1344
+ * @returns {Promise<RefInventory>}
1345
+ */
1346
+ export async function readRefInventory(cas) {
1347
+ const [service, vault] = await Promise.all([
1348
+ cas.getService(),
1349
+ cas.getVaultService(),
1350
+ ]);
1351
+
1352
+ let output = '';
1353
+ try {
1354
+ output = await service.persistence.plumbing.execute({ args: ['show-ref'] });
1355
+ } catch {
1356
+ return { namespaces: [], refs: [] };
1357
+ }
1358
+
1359
+ const refs = await Promise.all(output
1360
+ .split('\n')
1361
+ .map((row) => row.trim())
1362
+ .filter(Boolean)
1363
+ .map((line) => classifyRefLine(cas, { service, vault }, line)));
1364
+
1365
+ return {
1366
+ namespaces: summarizeRefNamespaces(refs),
1367
+ refs: refs.sort((left, right) =>
1368
+ Number(right.browsable) - Number(left.browsable)
1369
+ || left.namespace.localeCompare(right.namespace)
1370
+ || left.ref.localeCompare(right.ref)),
1371
+ };
1372
+ }
1373
+
1374
+ /**
1375
+ * Build the semantic repo/source treemap report for the dashboard.
1376
+ *
1377
+ * @param {ContentAddressableStore} cas
1378
+ * @param {{
1379
+ * source?: DashSource,
1380
+ * scope?: TreemapScope,
1381
+ * worktreeMode?: TreemapWorktreeMode,
1382
+ * drillPath?: TreemapPathNode[],
1383
+ * }} [options]
1384
+ * @returns {Promise<RepoTreemapReport>}
1385
+ */
1386
+ export async function buildRepoTreemapReport(cas, options = {}) {
1387
+ const {
1388
+ source = { type: 'vault' },
1389
+ scope = 'repository',
1390
+ worktreeMode = 'tracked',
1391
+ drillPath = [],
1392
+ } = options;
1393
+ const service = await cas.getService();
1394
+ const repo = await resolveRepoInfo(service.persistence.plumbing);
1395
+ const sourceResult = await readSourceEntries(cas, source);
1396
+ const sourceRecords = await loadEntryRecords(cas, sourceResult.entries);
1397
+
1398
+ if (scope === 'source') {
1399
+ return buildSourceScopeReport({ repo, source, sourceResult, sourceRecords, drillPath });
1400
+ }
1401
+ return buildRepositoryScopeReport({
1402
+ cas,
1403
+ source,
1404
+ repo,
1405
+ plumbing: service.persistence.plumbing,
1406
+ sourceResult,
1407
+ sourceRecords,
1408
+ worktreeMode,
1409
+ drillPath,
1410
+ });
1411
+ }
6
1412
 
7
1413
  /**
8
1414
  * Load vault entries and metadata in parallel.
9
1415
  *
10
1416
  * @param {ContentAddressableStore} cas
1417
+ * @param {DashSource} [source]
11
1418
  */
12
- export function loadEntriesCmd(cas) {
1419
+ export function loadEntriesCmd(cas, source = { type: 'vault' }) {
13
1420
  return async () => {
14
1421
  try {
15
- const [entries, metadata] = await Promise.all([
16
- cas.listVault(),
17
- cas.getVaultMetadata(),
18
- ]);
19
- return /** @type {const} */ ({ type: 'loaded-entries', entries, metadata });
1422
+ const { entries, metadata } = await readSourceEntries(cas, source);
1423
+ return /** @type {const} */ ({ type: 'loaded-entries', entries, metadata, source });
20
1424
  } catch (/** @type {any} */ err) {
21
- return /** @type {const} */ ({ type: 'load-error', source: 'entries', error: /** @type {Error} */ (err).message });
1425
+ return /** @type {const} */ ({ type: 'load-error', source: 'entries', forSource: source, error: /** @type {Error} */ (err).message });
22
1426
  }
23
1427
  };
24
1428
  }
@@ -27,16 +1431,177 @@ export function loadEntriesCmd(cas) {
27
1431
  * Load a single manifest by slug and tree OID.
28
1432
  *
29
1433
  * @param {ContentAddressableStore} cas
30
- * @param {string} slug
31
- * @param {string} treeOid
1434
+ * @param {{ slug: string, treeOid: string, source: DashSource }} request
32
1435
  */
33
- export function loadManifestCmd(cas, slug, treeOid) {
1436
+ export function loadManifestCmd(cas, request) {
34
1437
  return async () => {
35
1438
  try {
36
- const manifest = await cas.readManifest({ treeOid });
37
- return /** @type {const} */ ({ type: 'loaded-manifest', slug, manifest });
1439
+ const manifest = await cas.readManifest({ treeOid: request.treeOid });
1440
+ return /** @type {const} */ ({ type: 'loaded-manifest', slug: request.slug, manifest, source: request.source });
38
1441
  } catch (/** @type {any} */ err) {
39
- return /** @type {const} */ ({ type: 'load-error', source: 'manifest', slug, error: /** @type {Error} */ (err).message });
1442
+ return /** @type {const} */ ({ type: 'load-error', source: 'manifest', slug: request.slug, forSource: request.source, error: /** @type {Error} */ (err).message });
1443
+ }
1444
+ };
1445
+ }
1446
+
1447
+ /**
1448
+ * Load the current repository ref inventory for the dashboard refs browser.
1449
+ *
1450
+ * @param {ContentAddressableStore} cas
1451
+ */
1452
+ export function loadRefsCmd(cas) {
1453
+ return async () => {
1454
+ try {
1455
+ const refs = await readRefInventory(cas);
1456
+ return /** @type {const} */ ({ type: 'loaded-refs', refs });
1457
+ } catch (/** @type {any} */ err) {
1458
+ return /** @type {const} */ ({ type: 'load-error', source: 'refs', error: /** @type {Error} */ (err).message });
1459
+ }
1460
+ };
1461
+ }
1462
+
1463
+ /**
1464
+ * Load aggregate vault stats for the current vault.
1465
+ *
1466
+ * @param {ContentAddressableStore} cas
1467
+ * @param {ExplorerEntry[]} entries
1468
+ * @param {DashSource} source
1469
+ */
1470
+ export function loadStatsCmd(cas, entries, source) {
1471
+ return async () => {
1472
+ try {
1473
+ const records = await Promise.all(entries.map(async (entry) => ({
1474
+ ...entry,
1475
+ manifest: await cas.readManifest({ treeOid: entry.treeOid }),
1476
+ })));
1477
+ return /** @type {const} */ ({ type: 'loaded-stats', stats: buildVaultStats(records), source });
1478
+ } catch (/** @type {any} */ err) {
1479
+ return /** @type {const} */ ({ type: 'load-error', source: 'stats', forSource: source, error: /** @type {Error} */ (err).message });
1480
+ }
1481
+ };
1482
+ }
1483
+
1484
+ /**
1485
+ * Load the doctor report for the current vault.
1486
+ *
1487
+ * @param {ContentAddressableStore} cas
1488
+ * @param {DashSource | {
1489
+ * source?: DashSource,
1490
+ * entries?: ExplorerEntry[],
1491
+ * encryptionKey?: Uint8Array | null,
1492
+ * }} [source]
1493
+ * @param {ExplorerEntry[]} [entries]
1494
+ */
1495
+ export function loadDoctorCmd(cas, source = { type: 'vault' }, entries = []) {
1496
+ const input = doctorCmdInput(source, entries);
1497
+ return async () => {
1498
+ try {
1499
+ if (input.source.type !== 'vault') {
1500
+ const target = input.source.type === 'ref' ? input.source.ref : input.source.treeOid;
1501
+ const report = `source: ${input.source.type}\n`
1502
+ + `target: ${target}\n`
1503
+ + `entries: ${input.entries.length}\n\n`
1504
+ + 'Repo-wide doctor currently targets vault mode. Use this source mode to inspect manifests and source-local stats.';
1505
+ return /** @type {const} */ ({ type: 'loaded-doctor', report, source: input.source });
1506
+ }
1507
+ const report = await inspectVaultHealth(cas, doctorInspectionOptions(input));
1508
+ return /** @type {const} */ ({ type: 'loaded-doctor', report, source: input.source });
1509
+ } catch (/** @type {any} */ err) {
1510
+ return /** @type {const} */ ({ type: 'load-error', source: 'doctor', forSource: input.source, error: /** @type {Error} */ (err).message });
1511
+ }
1512
+ };
1513
+ }
1514
+
1515
+ /**
1516
+ * @param {DashSource | { source?: DashSource, entries?: ExplorerEntry[], encryptionKey?: Uint8Array | null }} source
1517
+ * @param {ExplorerEntry[]} entries
1518
+ * @returns {{ source: DashSource, entries: ExplorerEntry[], encryptionKey?: Uint8Array | null }}
1519
+ */
1520
+ function doctorCmdInput(source, entries) {
1521
+ if (isDoctorCmdOptions(source)) {
1522
+ return {
1523
+ source: source.source || { type: 'vault' },
1524
+ entries: source.entries || [],
1525
+ encryptionKey: source.encryptionKey,
1526
+ };
1527
+ }
1528
+ return { source, entries };
1529
+ }
1530
+
1531
+ /**
1532
+ * @param {unknown} value
1533
+ * @returns {value is { source?: DashSource, entries?: ExplorerEntry[], encryptionKey?: Uint8Array | null }}
1534
+ */
1535
+ function isDoctorCmdOptions(value) {
1536
+ return Boolean(
1537
+ value &&
1538
+ typeof value === 'object' &&
1539
+ (
1540
+ Object.hasOwn(value, 'source') ||
1541
+ Object.hasOwn(value, 'entries') ||
1542
+ Object.hasOwn(value, 'encryptionKey')
1543
+ )
1544
+ );
1545
+ }
1546
+
1547
+ /**
1548
+ * @param {{ encryptionKey?: Uint8Array | null }} options
1549
+ * @returns {{ encryptionKey?: Uint8Array }}
1550
+ */
1551
+ function doctorInspectionOptions({ encryptionKey } = {}) {
1552
+ return encryptionKey ? { encryptionKey } : {};
1553
+ }
1554
+
1555
+ /**
1556
+ * Load the repository/source treemap report for the dashboard drawer.
1557
+ *
1558
+ * @param {ContentAddressableStore} cas
1559
+ * @param {{
1560
+ * source?: DashSource,
1561
+ * scope?: TreemapScope,
1562
+ * worktreeMode?: TreemapWorktreeMode,
1563
+ * drillPath?: TreemapPathNode[],
1564
+ * }} [options]
1565
+ */
1566
+ export function loadTreemapCmd(cas, options = {}) {
1567
+ const {
1568
+ source = { type: 'vault' },
1569
+ scope = 'repository',
1570
+ worktreeMode = 'tracked',
1571
+ drillPath = [],
1572
+ } = options;
1573
+ return async () => {
1574
+ try {
1575
+ const report = await buildRepoTreemapReport(cas, { source, scope, worktreeMode, drillPath });
1576
+ return /** @type {const} */ ({ type: 'loaded-treemap', report });
1577
+ } catch (/** @type {any} */ err) {
1578
+ return /** @type {const} */ ({
1579
+ type: 'load-error',
1580
+ source: 'treemap',
1581
+ scopeId: scope,
1582
+ worktreeMode,
1583
+ drillPath,
1584
+ error: /** @type {Error} */ (err).message,
1585
+ });
1586
+ }
1587
+ };
1588
+ }
1589
+
1590
+ /**
1591
+ * Load the current git branch name for the status bar.
1592
+ *
1593
+ * @param {ContentAddressableStore} cas
1594
+ */
1595
+ export function loadBranchCmd(cas) {
1596
+ return async () => {
1597
+ try {
1598
+ const service = await cas.getService();
1599
+ const branch = (await service.persistence.plumbing.execute({
1600
+ args: ['branch', '--show-current'],
1601
+ })).trim();
1602
+ return /** @type {const} */ ({ type: 'loaded-branch', branch: branch || null });
1603
+ } catch {
1604
+ return /** @type {const} */ ({ type: 'loaded-branch', branch: null });
40
1605
  }
41
1606
  };
42
1607
  }