@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
@@ -1,306 +1,1090 @@
1
1
  /**
2
- * TEA app shell for the vault dashboard.
2
+ * TEA app shell for the V6 git-cas cockpit.
3
3
  */
4
4
 
5
- import { run, quit, createKeyMap } from '@flyingrobots/bijou-tui';
6
- import { createNodeContext } from '@flyingrobots/bijou-node';
7
- import { loadEntriesCmd, loadManifestCmd } from './dashboard-cmds.js';
8
- import { renderDashboard } from './dashboard-view.js';
5
+ import { startApp as bijouStartApp } from '@flyingrobots/bijou-node';
6
+ import {
7
+ cpFilter,
8
+ cpFocusNext,
9
+ cpFocusPrev,
10
+ cpPageDown,
11
+ cpPageUp,
12
+ cpSelectedItem,
13
+ createCommandPaletteState,
14
+ createNavigableTableState,
15
+ createNotificationState,
16
+ navTableFocusNext,
17
+ navTableFocusPrev,
18
+ navTablePageDown,
19
+ navTablePageUp,
20
+ notificationsNeedTick,
21
+ pushNotification,
22
+ quit,
23
+ tick as bijouTick,
24
+ tickNotifications,
25
+ } from '@flyingrobots/bijou-tui';
26
+ import { renderDashboard, tableSchema } from './dashboard-view.js';
27
+ import { createCliTuiContext } from './context.js';
28
+ import { formatTabSeparated } from './vault-list.js';
29
+ import {
30
+ loadBranchCmd,
31
+ loadDoctorCmd,
32
+ loadEntriesCmd,
33
+ loadManifestCmd,
34
+ loadRefsCmd,
35
+ loadStatsCmd,
36
+ loadTreemapCmd,
37
+ readSourceEntries,
38
+ } from './dashboard-cmds.js';
39
+ import { createWizardState, wizardHandleKey } from './store-wizard.js';
40
+ import { createFeedState } from './blocks/operation-feed.js';
41
+ import { shortenSha } from './components/short-sha.js';
9
42
 
10
- /**
11
- * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
12
- * @typedef {import('@flyingrobots/bijou-tui').KeyMsg} KeyMsg
13
- * @typedef {import('@flyingrobots/bijou-tui').ResizeMsg} ResizeMsg
14
- * @typedef {import('@flyingrobots/bijou-tui').Cmd<DashMsg>} DashCmd
15
- * @typedef {import('@flyingrobots/bijou-tui').KeyMap<DashAction>} DashKeyMap
16
- * @typedef {import('../../index.js').default} ContentAddressableStore
17
- * @typedef {import('../../src/domain/value-objects/Manifest.js').default} Manifest
18
- * @typedef {{ slug: string, treeOid: string }} VaultEntry
19
- */
20
-
21
- /**
22
- * @typedef {{ type: 'quit' }
23
- * | { type: 'move', delta: number }
24
- * | { type: 'select' }
25
- * | { type: 'filter-start' }
26
- * | { type: 'scroll-detail', delta: number }
27
- * } DashAction
28
- */
43
+ /** @typedef {import('../index.js').default} ContentAddressableStore */
44
+ /** @typedef {import('../src/domain/value-objects/Manifest.js').default} Manifest */
45
+ /** @typedef {import('../src/domain/services/VaultService.js').VaultEntry} VaultEntry */
46
+ /** @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext */
47
+ /** @typedef {import('@flyingrobots/bijou-tui').CommandPaletteState} CommandPaletteState */
48
+ /** @typedef {import('@flyingrobots/bijou-tui').NavigableTableState} NavigableTableState */
49
+ /** @typedef {import('@flyingrobots/bijou-tui').NotificationState} NotificationState */
50
+ /** @typedef {import('./store-wizard.js').StoreWizardState} StoreWizardState */
51
+ /** @typedef {import('./blocks/operation-feed.js').OperationFeedState} OperationFeedState */
29
52
 
30
53
  /**
31
- * @typedef {{ type: 'loaded-entries', entries: VaultEntry[], metadata: any }
32
- * | { type: 'loaded-manifest', slug: string, manifest: Manifest }
33
- * | { type: 'load-error', source: string, slug?: string, error: string }
34
- * } DashMsg
54
+ * @typedef {'title' | 'password' | 'dashboard'} AppPhase
55
+ * @typedef {'explorer' | 'atlas' | 'operations'} WorkspaceId
56
+ * @typedef {'ledger' | 'manifest' | 'merkle'} ExplorerMode
57
+ * @typedef {'table' | 'tree' | 'dag'} MerkleMode
58
+ * @typedef {{ type: 'vault' } | { type: 'ref', ref: string } | { type: 'oid', treeOid: string }} DashSource
35
59
  */
36
60
 
37
61
  /**
38
62
  * @typedef {Object} DashModel
63
+ * @property {AppPhase} phase
64
+ * @property {number} titleTimeMs
65
+ * @property {number} lastTickTime
66
+ * @property {number} fps
67
+ * @property {boolean} showPerfHud
68
+ * @property {number} vaultEntryCount
69
+ * @property {string} passphrase
70
+ * @property {string | null} authError
39
71
  * @property {string} status
40
72
  * @property {number} columns
41
73
  * @property {number} rows
74
+ * @property {DashSource} source
75
+ * @property {WorkspaceId} workspace
76
+ * @property {ExplorerMode} explorerMode
77
+ * @property {MerkleMode} merkleMode
78
+ * @property {'ledger' | 'detail'} focusPane
79
+ * @property {number} chunkFocus
42
80
  * @property {VaultEntry[]} entries
43
81
  * @property {VaultEntry[]} filtered
44
- * @property {number} cursor
45
82
  * @property {string} filterText
46
83
  * @property {boolean} filtering
47
84
  * @property {any} metadata
48
85
  * @property {Map<string, Manifest>} manifestCache
49
86
  * @property {string | null} loadingSlug
50
- * @property {number} detailScroll
51
87
  * @property {string | null} error
88
+ * @property {NavigableTableState} table
89
+ * @property {CommandPaletteState | null} palette
90
+ * @property {boolean} showHelp
91
+ * @property {boolean} promptEnter
92
+ * @property {boolean} quitConfirm
93
+ * @property {any} refsStatus
94
+ * @property {any | null} refsInventory
95
+ * @property {string | null} refsError
96
+ * @property {any} statsStatus
97
+ * @property {any | null} statsReport
98
+ * @property {string | null} statsError
99
+ * @property {any} doctorStatus
100
+ * @property {any | null} doctorReport
101
+ * @property {string | null} doctorError
102
+ * @property {any} treemapScope
103
+ * @property {any} treemapWorktreeMode
104
+ * @property {any[]} treemapPath
105
+ * @property {number} treemapFocus
106
+ * @property {any} treemapStatus
107
+ * @property {any | null} treemapReport
108
+ * @property {string | null} treemapError
109
+ * @property {NotificationState} notifications
110
+ * @property {OperationFeedState} operationFeed
111
+ * @property {StoreWizardState | null} storeWizard
112
+ * @property {string | null} gitBranch
113
+ * @property {Buffer | null} vaultEncryptionKey
114
+ * @property {boolean} settingsOpen
52
115
  */
53
116
 
54
117
  /**
55
118
  * @typedef {Object} DashDeps
56
- * @property {DashKeyMap} keyMap
57
119
  * @property {ContentAddressableStore} cas
58
120
  * @property {BijouContext} ctx
121
+ * @property {string} cwdLabel
122
+ * @property {DashSource} source
123
+ * @property {(ms: number, msg: any) => any} tick
59
124
  */
60
125
 
61
- /**
62
- * Create keyboard bindings for normal mode.
63
- *
64
- * @returns {DashKeyMap}
65
- */
66
- export function createKeyBindings() {
67
- return createKeyMap()
68
- .bind('q', 'Quit', { type: 'quit' })
69
- .bind('j', 'Down', { type: 'move', delta: 1 })
70
- .bind('down', 'Down', { type: 'move', delta: 1 })
71
- .bind('k', 'Up', { type: 'move', delta: -1 })
72
- .bind('up', 'Up', { type: 'move', delta: -1 })
73
- .bind('enter', 'Load', { type: 'select' })
74
- .bind('/', 'Filter', { type: 'filter-start' })
75
- .bind('shift+j', 'Scroll down', { type: 'scroll-detail', delta: 3 })
76
- .bind('shift+k', 'Scroll up', { type: 'scroll-detail', delta: -3 });
126
+ const TITLE_TICK_MS = 33;
127
+ const NOTIFICATION_TICK_MS = 40;
128
+
129
+ const FULL_COLUMNS = [
130
+ { header: 'Slug' },
131
+ { header: 'Tree OID' },
132
+ { header: 'Size' },
133
+ { header: 'Chunks' },
134
+ { header: 'Crypto' },
135
+ { header: 'Format' },
136
+ { header: 'State' },
137
+ ];
138
+
139
+ function formatSize(bytes) {
140
+ if (!Number.isFinite(bytes)) { return '-'; }
141
+ if (bytes < 1024) { return `${bytes}B`; }
142
+ if (bytes < 1024 * 1024) { return `${(bytes / 1024).toFixed(1)}K`; }
143
+ if (bytes < 1024 * 1024 * 1024) { return `${(bytes / (1024 * 1024)).toFixed(1)}M`; }
144
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}G`;
77
145
  }
78
146
 
79
- /**
80
- * Create the initial model.
81
- *
82
- * @returns {DashModel}
83
- */
84
- function createInitModel() {
147
+ function manifestData(manifest) {
148
+ return manifest?.toJSON ? manifest.toJSON() : manifest;
149
+ }
150
+
151
+ function manifestFor(entry, manifestCache) {
152
+ return entry ? manifestData(manifestCache.get(entry.slug)) : null;
153
+ }
154
+
155
+ function cryptoLabel(manifest) {
156
+ if (!manifest) { return '-'; }
157
+ if (manifest.encryption?.encrypted || manifest.encryption?.recipients?.length || manifest.encryption) {
158
+ return 'encrypted';
159
+ }
160
+ return 'plain';
161
+ }
162
+
163
+ function formatLabel(manifest) {
164
+ if (!manifest) { return '-'; }
165
+ return manifest.formatVersion ?? (manifest.version ? `v${manifest.version}` : 'manifest');
166
+ }
167
+
168
+ function chunkLabel(manifest) {
169
+ if (!manifest) { return '-'; }
170
+ const chunks = manifest.chunks?.length ?? 0;
171
+ const subManifests = manifest.subManifests?.length ?? 0;
172
+ return subManifests > 0 ? `${chunks}+${subManifests}` : String(chunks);
173
+ }
174
+
175
+ function rowForEntry(entry, manifestCache) {
176
+ const manifest = manifestFor(entry, manifestCache);
177
+ return [
178
+ entry.slug,
179
+ shortenSha(entry.treeOid),
180
+ formatSize(manifest?.size),
181
+ chunkLabel(manifest),
182
+ cryptoLabel(manifest),
183
+ formatLabel(manifest),
184
+ manifest ? 'loaded' : 'pending',
185
+ ];
186
+ }
187
+
188
+ function buildTableRows(entries, manifestCache) {
189
+ return entries.map((entry) => rowForEntry(entry, manifestCache));
190
+ }
191
+
192
+ function tableHeight(rows) {
193
+ return Math.max(4, Math.min(18, Math.max(1, rows - 10)));
194
+ }
195
+
196
+ function sourceEquals(left, right) {
197
+ return JSON.stringify(left) === JSON.stringify(right);
198
+ }
199
+
200
+ function filterEntries(entries, filterText, manifestCache) {
201
+ const query = filterText.trim().toLowerCase();
202
+ if (!query) { return entries; }
203
+ return entries.filter((entry) => {
204
+ const manifest = manifestFor(entry, manifestCache);
205
+ const haystack = [
206
+ entry.slug,
207
+ entry.treeOid,
208
+ manifest?.integrity,
209
+ manifest?.hash,
210
+ ...(manifest?.chunks ?? []).flatMap((chunk) => [chunk.digest, chunk.blob]),
211
+ ].filter(Boolean).join(' ').toLowerCase();
212
+ return haystack.includes(query);
213
+ });
214
+ }
215
+
216
+ function syncExplorer(model, patch = {}) {
217
+ const next = { ...model, ...patch };
218
+ const filtered = filterEntries(next.entries, next.filterText, next.manifestCache);
219
+ const table = createNavigableTableState({
220
+ columns: FULL_COLUMNS,
221
+ rows: buildTableRows(filtered, next.manifestCache),
222
+ height: tableHeight(next.rows),
223
+ focusRow: Math.min(next.table?.focusRow ?? 0, Math.max(0, filtered.length - 1)),
224
+ scrollY: next.table?.scrollY ?? 0,
225
+ });
226
+ return { ...next, filtered, table };
227
+ }
228
+
229
+ function selectedEntry(model) {
230
+ return model.filtered[Math.min(model.table.focusRow, Math.max(0, model.filtered.length - 1))] ?? null;
231
+ }
232
+
233
+ function selectedManifest(model) {
234
+ return manifestFor(selectedEntry(model), model.manifestCache);
235
+ }
236
+
237
+ function maybeLoadSelectedManifest(model, deps) {
238
+ const entry = selectedEntry(model);
239
+ if (!entry || model.manifestCache.has(entry.slug) || model.loadingSlug === entry.slug) {
240
+ return null;
241
+ }
242
+ return loadManifestCmd(deps.cas, { slug: entry.slug, treeOid: entry.treeOid, source: model.source });
243
+ }
244
+
245
+ function createShellState(columns, rows, source) {
246
+ return {
247
+ phase: 'title',
248
+ titleTimeMs: 0,
249
+ lastTickTime: 0,
250
+ fps: 0,
251
+ showPerfHud: false,
252
+ vaultEntryCount: 0,
253
+ passphrase: '',
254
+ authError: null,
255
+ status: 'checking vault',
256
+ columns,
257
+ rows,
258
+ source,
259
+ workspace: 'explorer',
260
+ explorerMode: 'ledger',
261
+ merkleMode: 'table',
262
+ focusPane: 'ledger',
263
+ chunkFocus: 0,
264
+ promptEnter: false,
265
+ quitConfirm: false,
266
+ gitBranch: null,
267
+ vaultEncryptionKey: null,
268
+ settingsOpen: false,
269
+ };
270
+ }
271
+
272
+ function createExplorerState(rows) {
85
273
  return {
86
- status: 'loading',
87
- columns: process.stdout.columns ?? 80,
88
- rows: process.stdout.rows ?? 24,
89
274
  entries: [],
90
275
  filtered: [],
91
- cursor: 0,
92
276
  filterText: '',
93
277
  filtering: false,
94
278
  metadata: null,
95
279
  manifestCache: new Map(),
96
280
  loadingSlug: null,
97
- detailScroll: 0,
98
281
  error: null,
282
+ table: createNavigableTableState({ columns: FULL_COLUMNS, rows: [], height: tableHeight(rows) }),
283
+ palette: null,
284
+ showHelp: false,
99
285
  };
100
286
  }
101
287
 
102
- /**
103
- * Apply filter text to entries.
104
- *
105
- * @param {VaultEntry[]} entries
106
- * @param {string} text
107
- * @returns {VaultEntry[]}
108
- */
109
- function applyFilter(entries, text) {
110
- if (!text) { return entries; }
111
- return entries.filter((/** @type {VaultEntry} */ e) => e.slug.includes(text));
288
+ function createServiceState() {
289
+ return {
290
+ refsStatus: 'idle',
291
+ refsInventory: null,
292
+ refsError: null,
293
+ statsStatus: 'idle',
294
+ statsReport: null,
295
+ statsError: null,
296
+ doctorStatus: 'idle',
297
+ doctorReport: null,
298
+ doctorError: null,
299
+ treemapScope: 'repository',
300
+ treemapWorktreeMode: 'tracked',
301
+ treemapPath: [],
302
+ treemapFocus: 0,
303
+ treemapStatus: 'idle',
304
+ treemapReport: null,
305
+ treemapError: null,
306
+ notifications: createNotificationState(),
307
+ operationFeed: createFeedState(),
308
+ storeWizard: null,
309
+ };
112
310
  }
113
311
 
114
- /**
115
- * Handle the loaded-entries message.
116
- *
117
- * @param {DashMsg & { type: 'loaded-entries' }} msg
118
- * @param {DashModel} model
119
- * @param {ContentAddressableStore} cas
120
- * @returns {[DashModel, DashCmd[]]}
121
- */
122
- function handleLoadedEntries(msg, model, cas) {
123
- const filtered = applyFilter(msg.entries, model.filterText);
124
- const cursor = Math.max(0, Math.min(model.cursor, filtered.length - 1));
125
- const cmds = /** @type {DashCmd[]} */ (msg.entries.map((/** @type {VaultEntry} */ e) => loadManifestCmd(cas, e.slug, e.treeOid)));
312
+ function createInitModel(ctx, source) {
313
+ const rows = ctx.runtime.rows ?? 24;
314
+ const columns = ctx.runtime.columns ?? 80;
315
+ return syncExplorer({
316
+ ...createShellState(columns, rows, source),
317
+ ...createExplorerState(rows),
318
+ ...createServiceState(),
319
+ });
320
+ }
321
+
322
+ function checkVaultAuthCmd(cas) {
323
+ return async () => {
324
+ let metadata = null;
325
+ try {
326
+ metadata = await cas.getVaultMetadata();
327
+ } catch {
328
+ metadata = null;
329
+ }
330
+ if (metadata?.encryption) {
331
+ return { type: 'vault-auth-check', encrypted: true, entryCount: 0, metadata };
332
+ }
333
+ try {
334
+ const all = await cas.listVault();
335
+ return { type: 'vault-auth-check', encrypted: Boolean(metadata?.encryption), entryCount: all.length, metadata };
336
+ } catch {
337
+ return { type: 'vault-auth-check', encrypted: false, entryCount: 0, metadata: null };
338
+ }
339
+ };
340
+ }
341
+
342
+ async function deriveVaultKey(cas, metadata, passphrase) {
343
+ const kdf = metadata?.encryption?.kdf;
344
+ if (!kdf) { throw new Error('Missing vault encryption KDF metadata'); }
345
+ const { key } = await cas.deriveKey({
346
+ passphrase,
347
+ salt: Buffer.from(kdf.salt, 'base64'),
348
+ algorithm: kdf.algorithm,
349
+ iterations: kdf.iterations,
350
+ cost: kdf.cost,
351
+ blockSize: kdf.blockSize,
352
+ parallelization: kdf.parallelization,
353
+ keyLength: kdf.keyLength,
354
+ });
355
+ return key;
356
+ }
357
+
358
+ async function verifyVaultKeyAgainstEntries(cas, entries, encryptionKey) {
359
+ for (const entry of entries) {
360
+ const manifest = await cas.readManifest({ treeOid: entry.treeOid });
361
+ const data = manifestData(manifest);
362
+ if (data?.encryption?.encrypted || data?.encryption) {
363
+ return await cas.verifyIntegrity(manifest, { encryptionKey });
364
+ }
365
+ }
366
+ return true;
367
+ }
368
+
369
+ function verifyPassphraseCmd(cas, passphrase) {
370
+ return async () => {
371
+ try {
372
+ const metadata = await cas.getVaultMetadata();
373
+ const encryptionKey = await deriveVaultKey(cas, metadata, passphrase);
374
+ const entries = await cas.listVault({ encryptionKey });
375
+ const ok = await verifyVaultKeyAgainstEntries(cas, entries, encryptionKey);
376
+ return ok
377
+ ? { type: 'vault-auth-ok', encryptionKey }
378
+ : { type: 'vault-auth-fail', error: 'Wrong passphrase' };
379
+ } catch (err) {
380
+ const authErrorCodes = ['INTEGRITY_ERROR', 'DEK_UNWRAP_FAILED', 'MISSING_KEY', 'NO_MATCHING_RECIPIENT'];
381
+ const msg = authErrorCodes.includes(err.code) ? 'Wrong passphrase' : (err.message ?? String(err));
382
+ return { type: 'vault-auth-fail', error: msg };
383
+ }
384
+ };
385
+ }
386
+
387
+ function casForModel(cas, model) {
388
+ if (!model.vaultEncryptionKey) { return cas; }
389
+ return new Proxy(cas, {
390
+ get(target, prop, receiver) {
391
+ if (prop === 'listVault') {
392
+ return (options = {}) => target.listVault({ ...options, encryptionKey: model.vaultEncryptionKey });
393
+ }
394
+ if (prop === 'addToVault') {
395
+ return (options = {}) => target.addToVault({ ...options, encryptionKey: model.vaultEncryptionKey });
396
+ }
397
+ const value = Reflect.get(target, prop, receiver);
398
+ return typeof value === 'function' ? value.bind(target) : value;
399
+ },
400
+ });
401
+ }
402
+
403
+ function runStoreWizardCmd(cas, wizard) {
404
+ return async () => {
405
+ try {
406
+ if (wizard.encryption !== 'none') {
407
+ return {
408
+ type: 'store-error',
409
+ error: 'The TUI store path currently supports plaintext store plans only. Use the CLI for passphrase or convergent encryption.',
410
+ };
411
+ }
412
+ const manifest = await cas.storeFile({
413
+ filePath: wizard.filePath,
414
+ slug: wizard.slug,
415
+ ...(wizard.compression ? { compression: { algorithm: 'gzip' } } : {}),
416
+ });
417
+ const treeOid = await cas.createTree({ manifest });
418
+ await cas.addToVault({ slug: wizard.slug, treeOid, force: true });
419
+ return { type: 'store-complete', slug: wizard.slug, treeOid, manifest };
420
+ } catch (err) {
421
+ return { type: 'store-error', error: err.message ?? String(err) };
422
+ }
423
+ };
424
+ }
425
+
426
+ function enterDashboard(model, deps) {
427
+ const cas = casForModel(deps.cas, model);
428
+ return [{
429
+ ...model,
430
+ phase: 'dashboard',
431
+ promptEnter: false,
432
+ authError: null,
433
+ status: 'loading entries',
434
+ }, [
435
+ loadEntriesCmd(cas, model.source),
436
+ loadBranchCmd(cas),
437
+ loadRefsCmd(cas),
438
+ ]];
439
+ }
440
+
441
+ function pushToast(model, spec) {
442
+ return {
443
+ ...model,
444
+ notifications: pushNotification(model.notifications, {
445
+ variant: 'TOAST',
446
+ placement: 'LOWER_RIGHT',
447
+ width: 42,
448
+ ...spec,
449
+ }, Date.now()),
450
+ };
451
+ }
452
+
453
+ function notificationTick(model, deps) {
454
+ return notificationsNeedTick(model.notifications)
455
+ ? [deps.tick(NOTIFICATION_TICK_MS, { type: 'notification-tick' })]
456
+ : [];
457
+ }
458
+
459
+ function handleTickMsg(msg, model, deps) {
460
+ if (msg.type === 'notification-tick') {
461
+ const next = { ...model, notifications: tickNotifications(model.notifications, Date.now()) };
462
+ return [next, notificationTick(next, deps)];
463
+ }
464
+ if (msg.type !== 'title-tick' || (model.phase !== 'title' && model.phase !== 'password')) {
465
+ return [model, []];
466
+ }
467
+ const now = Date.now();
468
+ const elapsed = now - (model.lastTickTime || now);
469
+ const fps = elapsed > 0 ? Math.round(1000 / elapsed) : 0;
470
+ return [{
471
+ ...model,
472
+ titleTimeMs: (model.titleTimeMs || 0) + TITLE_TICK_MS,
473
+ lastTickTime: now,
474
+ fps: model.lastTickTime ? fps : 0,
475
+ }, [deps.tick(TITLE_TICK_MS, { type: 'title-tick' })]];
476
+ }
477
+
478
+ function handleVaultAuthCheck(msg, model) {
479
+ if (msg.encrypted) {
480
+ return [{
481
+ ...model,
482
+ phase: 'password',
483
+ metadata: msg.metadata,
484
+ vaultEntryCount: msg.entryCount,
485
+ status: 'vault locked',
486
+ }, []];
487
+ }
126
488
  return [{
127
489
  ...model,
128
- status: 'ready',
490
+ metadata: msg.metadata,
491
+ promptEnter: true,
492
+ vaultEntryCount: msg.entryCount,
493
+ status: 'vault ready',
494
+ }, []];
495
+ }
496
+
497
+ function handleLoadedEntries(msg, model, deps) {
498
+ if (!sourceEquals(msg.source, model.source)) { return [model, []]; }
499
+ const next = syncExplorer(model, {
129
500
  entries: msg.entries,
130
- filtered,
131
- cursor,
132
501
  metadata: msg.metadata,
133
- }, cmds];
502
+ status: `${msg.entries.length} entries`,
503
+ error: null,
504
+ });
505
+ const manifestCmd = maybeLoadSelectedManifest(next, deps);
506
+ return [next, [
507
+ loadStatsCmd(deps.cas, msg.entries, model.source),
508
+ ...(manifestCmd ? [manifestCmd] : []),
509
+ ]];
134
510
  }
135
511
 
136
- /**
137
- * Handle a loaded-manifest message.
138
- *
139
- * @param {DashMsg & { type: 'loaded-manifest' }} msg
140
- * @param {DashModel} model
141
- * @returns {[DashModel, DashCmd[]]}
142
- */
143
512
  function handleLoadedManifest(msg, model) {
144
- const cache = new Map(model.manifestCache);
145
- cache.set(msg.slug, msg.manifest);
146
- return [{ ...model, manifestCache: cache }, []];
513
+ if (!sourceEquals(msg.source, model.source)) { return [model, []]; }
514
+ const manifestCache = new Map(model.manifestCache);
515
+ manifestCache.set(msg.slug, msg.manifest);
516
+ return [syncExplorer(model, { manifestCache, loadingSlug: null }), []];
147
517
  }
148
518
 
149
- /**
150
- * Handle cursor movement.
151
- *
152
- * @param {{ type: 'move', delta: number }} msg
153
- * @param {DashModel} model
154
- * @returns {[DashModel, DashCmd[]]}
155
- */
156
- function handleMove(msg, model) {
157
- const max = model.filtered.length - 1;
158
- const cursor = Math.max(0, Math.min(max, model.cursor + msg.delta));
159
- return [{ ...model, cursor, detailScroll: 0 }, []];
519
+ function handleLoadError(msg, model) {
520
+ let next = model;
521
+ const error = msg.error ?? 'Unknown dashboard error';
522
+ if (msg.source === 'entries') {
523
+ next = { ...next, status: 'entry load failed', error };
524
+ } else if (msg.source === 'manifest') {
525
+ next = { ...next, loadingSlug: null, error };
526
+ } else if (msg.source === 'refs') {
527
+ next = { ...next, refsStatus: 'error', refsError: error };
528
+ } else if (msg.source === 'stats') {
529
+ next = { ...next, statsStatus: 'error', statsError: error };
530
+ } else if (msg.source === 'doctor') {
531
+ next = { ...next, doctorStatus: 'error', doctorError: error };
532
+ } else if (msg.source === 'treemap') {
533
+ next = { ...next, treemapStatus: 'error', treemapError: error };
534
+ }
535
+ return [pushToast(next, { title: 'Dashboard load failed', message: error, tone: 'ERROR' }), []];
160
536
  }
161
537
 
162
- /**
163
- * Handle filter key input in filter mode.
164
- *
165
- * @param {KeyMsg} msg
166
- * @param {DashModel} model
167
- * @returns {[DashModel, DashCmd[]]}
168
- */
169
- function handleFilterKey(msg, model) {
170
- if (msg.key === 'escape' || msg.key === 'enter') {
171
- return [{ ...model, filtering: false }, []];
538
+ function handleAuthOkMsg(_msg, model, deps) {
539
+ return enterDashboard({ ...model, vaultEncryptionKey: _msg.encryptionKey ?? null }, deps);
540
+ }
541
+
542
+ function handleAuthFailMsg(msg, model) {
543
+ return [{ ...model, authError: msg.error, passphrase: '' }, []];
544
+ }
545
+
546
+ function handleLoadedRefsMsg(msg, model) {
547
+ return [{ ...model, refsStatus: 'ready', refsInventory: msg.refs, refsError: null }, []];
548
+ }
549
+
550
+ function handleLoadedStatsMsg(msg, model) {
551
+ if (!sourceEquals(msg.source, model.source)) { return [model, []]; }
552
+ return [{ ...model, statsStatus: 'ready', statsReport: msg.stats, statsError: null }, []];
553
+ }
554
+
555
+ function handleLoadedDoctorMsg(msg, model) {
556
+ if (!sourceEquals(msg.source, model.source)) { return [model, []]; }
557
+ return [{ ...model, doctorStatus: 'ready', doctorReport: msg.report, doctorError: null }, []];
558
+ }
559
+
560
+ function handleLoadedTreemapMsg(msg, model) {
561
+ return [{ ...model, treemapStatus: 'ready', treemapReport: msg.report, treemapFocus: 0, treemapError: null }, []];
562
+ }
563
+
564
+ function handleLoadedBranchMsg(msg, model) {
565
+ return [{ ...model, gitBranch: msg.branch }, []];
566
+ }
567
+
568
+ function handleStoreCompleteMsg(msg, model, deps) {
569
+ const manifestCache = new Map(model.manifestCache);
570
+ manifestCache.set(msg.slug, msg.manifest);
571
+ const next = pushToast({
572
+ ...syncExplorer(model, { manifestCache, storeWizard: null }),
573
+ operationFeed: completeLatestOperation(model.operationFeed, msg.slug, null),
574
+ }, { title: 'Stored asset', message: `${msg.slug} -> ${shortenSha(msg.treeOid)}`, tone: 'SUCCESS' });
575
+ return [next, [loadEntriesCmd(casForModel(deps.cas, model), model.source), ...notificationTick(next, deps)]];
576
+ }
577
+
578
+ function handleStoreErrorMsg(msg, model, deps) {
579
+ const next = pushToast({
580
+ ...model,
581
+ storeWizard: model.storeWizard ? { ...model.storeWizard, step: 'error', error: msg.error } : null,
582
+ operationFeed: completeLatestOperation(model.operationFeed, model.storeWizard?.slug ?? 'store', msg.error),
583
+ }, { title: 'Store failed', message: msg.error, tone: 'ERROR' });
584
+ return [next, notificationTick(next, deps)];
585
+ }
586
+
587
+ const APP_MSG_HANDLERS = {
588
+ 'notification-tick': handleTickMsg,
589
+ 'title-tick': handleTickMsg,
590
+ 'vault-auth-check': handleVaultAuthCheck,
591
+ 'vault-auth-ok': handleAuthOkMsg,
592
+ 'vault-auth-fail': handleAuthFailMsg,
593
+ 'loaded-entries': handleLoadedEntries,
594
+ 'loaded-manifest': handleLoadedManifest,
595
+ 'loaded-refs': handleLoadedRefsMsg,
596
+ 'loaded-stats': handleLoadedStatsMsg,
597
+ 'loaded-doctor': handleLoadedDoctorMsg,
598
+ 'loaded-treemap': handleLoadedTreemapMsg,
599
+ 'loaded-branch': handleLoadedBranchMsg,
600
+ 'store-complete': handleStoreCompleteMsg,
601
+ 'store-error': handleStoreErrorMsg,
602
+ 'load-error': handleLoadError,
603
+ };
604
+
605
+ function handleAppMsg(msg, model, deps) {
606
+ const handler = APP_MSG_HANDLERS[msg.type];
607
+ return handler ? handler(msg, model, deps) : [model, []];
608
+ }
609
+
610
+ function handleTitleKey(msg, model, deps) {
611
+ if (msg.key === '`') { return [{ ...model, showPerfHud: !model.showPerfHud }, []]; }
612
+ if (msg.key === 'q' || msg.key === 'escape') { return [model, [quit()]]; }
613
+ if (msg.key === 'enter' && model.promptEnter) { return enterDashboard(model, deps); }
614
+ return [model, []];
615
+ }
616
+
617
+ function handlePasswordKey(msg, model, deps) {
618
+ if (msg.key === '`') { return [{ ...model, showPerfHud: !model.showPerfHud }, []]; }
619
+ if (msg.key === 'escape') { return [model, [quit()]]; }
620
+ if (msg.key === 'enter') {
621
+ return [{ ...model, authError: null }, [verifyPassphraseCmd(deps.cas, model.passphrase)]];
172
622
  }
173
623
  if (msg.key === 'backspace') {
174
- const text = model.filterText.slice(0, -1);
175
- const filtered = applyFilter(model.entries, text);
176
- return [{ ...model, filterText: text, filtered, cursor: 0 }, []];
624
+ return [{ ...model, passphrase: model.passphrase.slice(0, -1) }, []];
177
625
  }
178
626
  if (msg.key.length === 1) {
179
- const text = model.filterText + msg.key;
180
- const filtered = applyFilter(model.entries, text);
181
- return [{ ...model, filterText: text, filtered, cursor: 0 }, []];
627
+ return [{ ...model, passphrase: model.passphrase + msg.key }, []];
182
628
  }
183
629
  return [model, []];
184
630
  }
185
631
 
186
- /**
187
- * Handle select (enter key) to load manifest.
188
- *
189
- * @param {DashModel} model
190
- * @param {DashDeps} deps
191
- * @returns {[DashModel, DashCmd[]]}
192
- */
193
- function handleSelect(model, deps) {
194
- const entry = model.filtered[model.cursor];
195
- if (!entry || model.manifestCache.has(entry.slug)) {
196
- return [model, []];
197
- }
198
- const cmd = /** @type {DashCmd} */ (loadManifestCmd(deps.cas, entry.slug, entry.treeOid));
199
- return [{ ...model, loadingSlug: entry.slug }, [cmd]];
632
+ function buildPaletteItems(model) {
633
+ return model.entries.map((entry) => {
634
+ const manifest = manifestFor(entry, model.manifestCache);
635
+ const digests = (manifest?.chunks ?? [])
636
+ .slice(0, 4)
637
+ .flatMap((chunk) => [chunk.digest, chunk.blob])
638
+ .filter(Boolean)
639
+ .join(' ');
640
+ return {
641
+ id: entry.slug,
642
+ label: entry.slug,
643
+ category: 'asset',
644
+ description: `${entry.treeOid} ${manifest?.integrity ?? ''} ${digests}`.trim(),
645
+ shortcut: 'enter',
646
+ };
647
+ });
200
648
  }
201
649
 
202
- /**
203
- * Handle keymap actions.
204
- *
205
- * @param {DashAction} action
206
- * @param {DashModel} model
207
- * @param {DashDeps} deps
208
- * @returns {[DashModel, DashCmd[]]}
209
- */
210
- function handleAction(action, model, deps) {
211
- if (action.type === 'quit') { return [model, [quit()]]; }
212
- if (action.type === 'move') { return handleMove(action, model); }
213
- if (action.type === 'filter-start') {
214
- return [{ ...model, filtering: true, filterText: '', filtered: model.entries, cursor: 0 }, []];
650
+ function openPalette(model) {
651
+ return {
652
+ ...model,
653
+ palette: createCommandPaletteState(buildPaletteItems(model), 9),
654
+ showHelp: false,
655
+ };
656
+ }
657
+
658
+ function selectPaletteItem(model, deps) {
659
+ const item = cpSelectedItem(model.palette);
660
+ if (!item) { return [{ ...model, palette: null }, []]; }
661
+ const selected = model.entries.find((entry) => entry.slug === item.id);
662
+ const next = syncExplorer(model, {
663
+ workspace: 'explorer',
664
+ explorerMode: 'manifest',
665
+ palette: null,
666
+ filterText: selected ? selected.slug : model.filterText,
667
+ filtering: false,
668
+ });
669
+ const manifestCmd = maybeLoadSelectedManifest(next, deps);
670
+ return [next, manifestCmd ? [manifestCmd] : []];
671
+ }
672
+
673
+ const PALETTE_ACTIONS = {
674
+ close: (_msg, model) => [{ ...model, palette: null }, []],
675
+ select: (_msg, model, deps) => selectPaletteItem(model, deps),
676
+ next: (_msg, model) => [{ ...model, palette: cpFocusNext(model.palette) }, []],
677
+ previous: (_msg, model) => [{ ...model, palette: cpFocusPrev(model.palette) }, []],
678
+ pageDown: (_msg, model) => [{ ...model, palette: cpPageDown(model.palette) }, []],
679
+ pageUp: (_msg, model) => [{ ...model, palette: cpPageUp(model.palette) }, []],
680
+ };
681
+
682
+ const PALETTE_KEY_ACTIONS = {
683
+ escape: 'close',
684
+ enter: 'select',
685
+ down: 'next',
686
+ up: 'previous',
687
+ pagedown: 'pageDown',
688
+ pageup: 'pageUp',
689
+ };
690
+
691
+ function paletteAction(msg) {
692
+ if (msg.ctrl && msg.key === 'n') { return 'next'; }
693
+ if (msg.ctrl && msg.key === 'p') { return 'previous'; }
694
+ if (msg.ctrl && msg.key === 'd') { return 'pageDown'; }
695
+ if (msg.ctrl && msg.key === 'u') { return 'pageUp'; }
696
+ return PALETTE_KEY_ACTIONS[msg.key] ?? null;
697
+ }
698
+
699
+ function paletteQueryForKey(msg, palette) {
700
+ if (msg.key === 'backspace') { return palette.query.slice(0, -1); }
701
+ if (msg.key.length === 1 && !msg.ctrl && !msg.alt) { return `${palette.query}${msg.key}`; }
702
+ return null;
703
+ }
704
+
705
+ function handlePaletteKey(msg, model, deps) {
706
+ if (!model.palette) { return [model, []]; }
707
+ const action = paletteAction(msg);
708
+ if (action) { return PALETTE_ACTIONS[action](msg, model, deps); }
709
+ const query = paletteQueryForKey(msg, model.palette);
710
+ return query === null
711
+ ? [model, []]
712
+ : [{ ...model, palette: cpFilter(model.palette, query) }, []];
713
+ }
714
+
715
+ function handleFilterKey(msg, model) {
716
+ if (msg.key === 'escape') { return [syncExplorer(model, { filtering: false }), []]; }
717
+ if (msg.key === 'enter') { return [syncExplorer(model, { filtering: false }), []]; }
718
+ if (msg.key === 'backspace') {
719
+ return [syncExplorer(model, { filterText: model.filterText.slice(0, -1) }), []];
215
720
  }
216
- if (action.type === 'scroll-detail') {
217
- const scroll = Math.max(0, model.detailScroll + action.delta);
218
- return [{ ...model, detailScroll: scroll }, []];
721
+ if (msg.key.length === 1 && !msg.ctrl && !msg.alt) {
722
+ return [syncExplorer(model, { filterText: `${model.filterText}${msg.key}` }), []];
219
723
  }
220
- if (action.type === 'select') { return handleSelect(model, deps); }
221
724
  return [model, []];
222
725
  }
223
726
 
224
- /**
225
- * Handle app-level messages (data loading results).
226
- *
227
- * @param {DashMsg} msg
228
- * @param {DashModel} model
229
- * @param {ContentAddressableStore} cas
230
- * @returns {[DashModel, DashCmd[]]}
231
- */
232
- function handleAppMsg(msg, model, cas) {
233
- if (msg.type === 'loaded-entries') { return handleLoadedEntries(msg, model, cas); }
234
- if (msg.type === 'loaded-manifest') { return handleLoadedManifest(msg, model); }
235
- if (msg.type === 'load-error') {
236
- if (msg.source === 'manifest') {
237
- return [model, []];
238
- }
239
- return [{ ...model, status: 'error', error: msg.error }, []];
727
+ const LEDGER_NAVIGATORS = {
728
+ j: navTableFocusNext,
729
+ down: navTableFocusNext,
730
+ k: navTableFocusPrev,
731
+ up: navTableFocusPrev,
732
+ d: navTablePageDown,
733
+ pagedown: navTablePageDown,
734
+ u: navTablePageUp,
735
+ pageup: navTablePageUp,
736
+ };
737
+
738
+ function handleExplorerNavigation(msg, model, deps) {
739
+ if (model.focusPane !== 'ledger') { return null; }
740
+ const navigate = LEDGER_NAVIGATORS[msg.key];
741
+ if (!navigate) { return null; }
742
+ const next = { ...model, table: navigate(model.table), chunkFocus: 0 };
743
+ const manifestCmd = maybeLoadSelectedManifest(next, deps);
744
+ return [next, manifestCmd ? [manifestCmd] : []];
745
+ }
746
+
747
+ function selectedChunks(model) {
748
+ return selectedManifest(model)?.chunks ?? [];
749
+ }
750
+
751
+ function clampChunkFocus(model, nextFocus) {
752
+ const chunks = selectedChunks(model);
753
+ return Math.max(0, Math.min(nextFocus, Math.max(0, chunks.length - 1)));
754
+ }
755
+
756
+ function chunkPageStep(model) {
757
+ return Math.max(1, Math.min(24, model.rows - 14));
758
+ }
759
+
760
+ function moveChunkFocus(model, delta) {
761
+ return [{ ...model, chunkFocus: clampChunkFocus(model, model.chunkFocus + delta) }, []];
762
+ }
763
+
764
+ function detailDeltaForKey(key, model) {
765
+ if (key === 'j' || key === 'down') { return 1; }
766
+ if (key === 'k' || key === 'up') { return -1; }
767
+ if (key === 'd' || key === 'pagedown') { return chunkPageStep(model); }
768
+ if (key === 'u' || key === 'pageup') { return -chunkPageStep(model); }
769
+ return null;
770
+ }
771
+
772
+ function handleDetailNavigation(msg, model) {
773
+ if (model.focusPane !== 'detail' || model.explorerMode === 'ledger') { return null; }
774
+ if (selectedChunks(model).length === 0) { return null; }
775
+ const delta = detailDeltaForKey(msg.key, model);
776
+ if (delta !== null) { return moveChunkFocus(model, delta); }
777
+ if (msg.key === 'g') { return [{ ...model, chunkFocus: 0 }, []]; }
778
+ return null;
779
+ }
780
+
781
+ function switchWorkspace(model, workspace, deps) {
782
+ const next = { ...model, workspace, showHelp: false };
783
+ if (workspace === 'atlas' && next.treemapStatus === 'idle') {
784
+ const cas = casForModel(deps.cas, next);
785
+ return [{ ...next, treemapStatus: 'loading' }, [loadTreemapCmd(cas, {
786
+ source: next.source,
787
+ scope: next.treemapScope,
788
+ worktreeMode: next.treemapWorktreeMode,
789
+ drillPath: next.treemapPath,
790
+ })]];
791
+ }
792
+ if (workspace === 'operations' && next.statsStatus === 'idle') {
793
+ return [{ ...next, statsStatus: 'loading' }, [loadStatsCmd(deps.cas, next.entries, next.source)]];
794
+ }
795
+ return [next, []];
796
+ }
797
+
798
+ function handleWorkspaceKey(msg, model, deps) {
799
+ if (msg.key === '1' || msg.key === 'e') { return switchWorkspace(model, 'explorer', deps); }
800
+ if (msg.key === '2' || msg.key === 'a') { return switchWorkspace(model, 'atlas', deps); }
801
+ if (msg.key === '3' || msg.key === 'o') { return switchWorkspace(model, 'operations', deps); }
802
+ return null;
803
+ }
804
+
805
+ function toggleExplorerDetail(model, deps) {
806
+ const enteringDetail = model.explorerMode === 'ledger';
807
+ const next = {
808
+ ...model,
809
+ explorerMode: enteringDetail ? 'manifest' : 'ledger',
810
+ focusPane: enteringDetail ? 'detail' : 'ledger',
811
+ };
812
+ const manifestCmd = maybeLoadSelectedManifest(next, deps);
813
+ return [next, manifestCmd ? [manifestCmd] : []];
814
+ }
815
+
816
+ function cycleMerkleMode(model) {
817
+ const modes = /** @type {MerkleMode[]} */ (['table', 'tree', 'dag']);
818
+ const nextMode = modes[(modes.indexOf(model.merkleMode) + 1) % modes.length];
819
+ return [{ ...model, explorerMode: 'merkle', merkleMode: nextMode, focusPane: 'detail' }, []];
820
+ }
821
+
822
+ function toggleInspectorMode(model, deps) {
823
+ const next = {
824
+ ...model,
825
+ explorerMode: model.explorerMode === 'manifest' ? 'merkle' : 'manifest',
826
+ focusPane: 'detail',
827
+ };
828
+ const manifestCmd = maybeLoadSelectedManifest(next, deps);
829
+ return [next, manifestCmd ? [manifestCmd] : []];
830
+ }
831
+
832
+ function handleExplorerModeKey(msg, model, deps) {
833
+ if (msg.key === 'enter') { return toggleExplorerDetail(model, deps); }
834
+ if (msg.key === 'm') { return cycleMerkleMode(model); }
835
+ if (msg.key === 'i') { return toggleInspectorMode(model, deps); }
836
+ return null;
837
+ }
838
+
839
+ function handleExplorerKey(msg, model, deps) {
840
+ if (msg.key === 'tab') {
841
+ return [{ ...model, focusPane: model.focusPane === 'ledger' ? 'detail' : 'ledger' }, []];
842
+ }
843
+ const detailNav = handleDetailNavigation(msg, model);
844
+ if (detailNav) { return detailNav; }
845
+ const nav = handleExplorerNavigation(msg, model, deps);
846
+ if (nav) { return nav; }
847
+ return handleExplorerModeKey(msg, model, deps);
848
+ }
849
+
850
+ function reloadTreemap(model, deps, patch = {}) {
851
+ const next = { ...model, ...patch, treemapStatus: 'loading', treemapError: null };
852
+ return [next, [loadTreemapCmd(casForModel(deps.cas, next), {
853
+ source: next.source,
854
+ scope: next.treemapScope,
855
+ worktreeMode: next.treemapWorktreeMode,
856
+ drillPath: next.treemapPath,
857
+ })]];
858
+ }
859
+
860
+ function focusAtlasTile(model, delta) {
861
+ const tiles = model.treemapReport?.tiles ?? [];
862
+ const maxFocus = Math.max(0, tiles.length - 1);
863
+ return [{ ...model, treemapFocus: Math.max(0, Math.min(model.treemapFocus + delta, maxFocus)) }, []];
864
+ }
865
+
866
+ function drillIntoAtlasTile(model, deps) {
867
+ const tile = model.treemapReport?.tiles?.[model.treemapFocus];
868
+ return tile?.drillable && tile.path
869
+ ? reloadTreemap(model, deps, { treemapPath: [...model.treemapPath, tile.path] })
870
+ : null;
871
+ }
872
+
873
+ function drillOutAtlasTile(model, deps) {
874
+ return model.treemapPath.length > 0
875
+ ? reloadTreemap(model, deps, { treemapPath: model.treemapPath.slice(0, -1) })
876
+ : null;
877
+ }
878
+
879
+ const ATLAS_KEY_ACTIONS = {
880
+ j: 'next',
881
+ down: 'next',
882
+ k: 'previous',
883
+ up: 'previous',
884
+ t: 'scope',
885
+ i: 'worktreeMode',
886
+ r: 'reload',
887
+ '+': 'drillIn',
888
+ enter: 'drillIn',
889
+ '-': 'drillOut',
890
+ backspace: 'drillOut',
891
+ };
892
+
893
+ const ATLAS_ACTIONS = {
894
+ next: (_msg, model) => focusAtlasTile(model, 1),
895
+ previous: (_msg, model) => focusAtlasTile(model, -1),
896
+ scope: (_msg, model, deps) => reloadTreemap(model, deps, { treemapScope: model.treemapScope === 'repository' ? 'source' : 'repository', treemapPath: [] }),
897
+ worktreeMode: (_msg, model, deps) => reloadTreemap(model, deps, { treemapWorktreeMode: model.treemapWorktreeMode === 'tracked' ? 'ignored' : 'tracked', treemapPath: [] }),
898
+ reload: (_msg, model, deps) => reloadTreemap(model, deps),
899
+ drillIn: (_msg, model, deps) => drillIntoAtlasTile(model, deps),
900
+ drillOut: (_msg, model, deps) => drillOutAtlasTile(model, deps),
901
+ };
902
+
903
+ function handleAtlasKey(msg, model, deps) {
904
+ const action = ATLAS_KEY_ACTIONS[msg.key];
905
+ return action ? ATLAS_ACTIONS[action](msg, model, deps) : null;
906
+ }
907
+
908
+ function startOperation(operationFeed, slug) {
909
+ return {
910
+ ...operationFeed,
911
+ entries: [{
912
+ id: `store-${slug}-${Date.now()}`,
913
+ type: 'store',
914
+ slug,
915
+ status: 'running',
916
+ startTime: Date.now(),
917
+ endTime: null,
918
+ chunksTotal: 0,
919
+ chunksProcessed: 0,
920
+ error: null,
921
+ }, ...operationFeed.entries].slice(0, operationFeed.maxEntries),
922
+ };
923
+ }
924
+
925
+ function completeLatestOperation(operationFeed, slug, error) {
926
+ return {
927
+ ...operationFeed,
928
+ entries: operationFeed.entries.map((entry, index) => {
929
+ if (index !== 0 || entry.slug !== slug) { return entry; }
930
+ return {
931
+ ...entry,
932
+ status: error ? 'error' : 'done',
933
+ endTime: Date.now(),
934
+ error,
935
+ };
936
+ }),
937
+ };
938
+ }
939
+
940
+ function handleWizardKey(msg, model, deps) {
941
+ if (!model.storeWizard) { return null; }
942
+ if (msg.key === 'escape') {
943
+ return [{ ...model, storeWizard: null }, []];
944
+ }
945
+ const nextWizard = wizardHandleKey(model.storeWizard, msg.key);
946
+ if (nextWizard.step === 'storing') {
947
+ return [{
948
+ ...model,
949
+ storeWizard: nextWizard,
950
+ operationFeed: startOperation(model.operationFeed, nextWizard.slug),
951
+ }, [runStoreWizardCmd(casForModel(deps.cas, model), nextWizard)]];
952
+ }
953
+ return [{ ...model, storeWizard: nextWizard }, []];
954
+ }
955
+
956
+ function handleOperationsKey(msg, model, deps) {
957
+ if (msg.key === 'n') { return [{ ...model, storeWizard: createWizardState() }, []]; }
958
+ if (msg.key === 's') {
959
+ return [{ ...model, statsStatus: 'loading', statsError: null }, [loadStatsCmd(deps.cas, model.entries, model.source)]];
960
+ }
961
+ if (msg.key === 'x') {
962
+ return [{
963
+ ...model,
964
+ doctorStatus: 'loading',
965
+ doctorError: null,
966
+ }, [loadDoctorCmd(deps.cas, {
967
+ source: model.source,
968
+ entries: model.entries,
969
+ encryptionKey: model.vaultEncryptionKey,
970
+ })]];
971
+ }
972
+ return null;
973
+ }
974
+
975
+ function handleQuitConfirmKey(msg, model) {
976
+ if (msg.key === 'y' || msg.key === 'enter') { return [model, [quit()]]; }
977
+ if (msg.key === 'n' || msg.key === 'escape' || msg.key === 'q') {
978
+ return [{ ...model, quitConfirm: false }, []];
240
979
  }
241
980
  return [model, []];
242
981
  }
243
982
 
244
- /**
245
- * Route all update messages to the appropriate handler.
246
- *
247
- * @param {KeyMsg | ResizeMsg | DashMsg} msg
248
- * @param {DashModel} model
249
- * @param {DashDeps} deps
250
- * @returns {[DashModel, DashCmd[]]}
251
- */
252
- function handleUpdate(msg, model, deps) {
253
- if (msg.type === 'key' && model.filtering) {
254
- return handleFilterKey(msg, model);
983
+ function clearDashboardOverlays(model) {
984
+ return {
985
+ ...model,
986
+ showHelp: false,
987
+ storeWizard: null,
988
+ palette: null,
989
+ filtering: false,
990
+ quitConfirm: false,
991
+ settingsOpen: false,
992
+ };
993
+ }
994
+
995
+ function handleOverlayShortcut(msg, model) {
996
+ if (msg.key === 'escape') { return [clearDashboardOverlays(model), []]; }
997
+ if (msg.key === 'f2') { return [{ ...model, settingsOpen: !model.settingsOpen, showHelp: false, palette: null }, []]; }
998
+ if (msg.key === '?' || (msg.shift && msg.key === '/')) {
999
+ return [{ ...model, showHelp: !model.showHelp, palette: null }, []];
255
1000
  }
1001
+ if (msg.key === 'q') { return [{ ...model, quitConfirm: true }, []]; }
1002
+ return null;
1003
+ }
1004
+
1005
+ function handleSearchShortcut(msg, model) {
1006
+ if (msg.key === '/' && !msg.ctrl) {
1007
+ return [syncExplorer(model, { workspace: 'explorer', filtering: true, palette: null }), []];
1008
+ }
1009
+ if ((msg.ctrl && msg.key === 'p') || msg.key === ':') { return [openPalette(model), []]; }
1010
+ return null;
1011
+ }
1012
+
1013
+ function handleGlobalDashboardKey(msg, model, deps) {
1014
+ const overlay = handleOverlayShortcut(msg, model);
1015
+ if (overlay) { return overlay; }
1016
+ const search = handleSearchShortcut(msg, model);
1017
+ if (search) { return search; }
1018
+ return handleWorkspaceKey(msg, model, deps);
1019
+ }
1020
+
1021
+ const WORKSPACE_KEY_HANDLERS = {
1022
+ explorer: handleExplorerKey,
1023
+ atlas: handleAtlasKey,
1024
+ operations: handleOperationsKey,
1025
+ };
1026
+
1027
+ function handleWorkspaceSpecificKey(msg, model, deps) {
1028
+ const handler = WORKSPACE_KEY_HANDLERS[model.workspace];
1029
+ return handler ? handler(msg, model, deps) : null;
1030
+ }
1031
+
1032
+ function handleDashboardKey(msg, model, deps) {
1033
+ if (model.quitConfirm) { return handleQuitConfirmKey(msg, model); }
1034
+ if (model.palette) { return handlePaletteKey(msg, model, deps); }
1035
+ const wizard = handleWizardKey(msg, model, deps);
1036
+ if (wizard) { return wizard; }
1037
+ if (model.filtering) { return handleFilterKey(msg, model); }
1038
+ const global = handleGlobalDashboardKey(msg, model, deps);
1039
+ return global ?? handleWorkspaceSpecificKey(msg, model, deps) ?? [model, []];
1040
+ }
1041
+
1042
+ function handleUpdate(msg, model, deps) {
256
1043
  if (msg.type === 'key') {
257
- const action = deps.keyMap.handle(msg);
258
- if (action) { return handleAction(action, model, deps); }
259
- return [model, []];
1044
+ if (model.phase === 'title') { return handleTitleKey(msg, model, deps); }
1045
+ if (model.phase === 'password') { return handlePasswordKey(msg, model, deps); }
1046
+ return handleDashboardKey(msg, model, deps);
260
1047
  }
261
1048
  if (msg.type === 'resize') {
262
- return [{ ...model, columns: msg.columns, rows: msg.rows }, []];
1049
+ return [syncExplorer(model, { columns: msg.columns, rows: msg.rows }), []];
263
1050
  }
264
- return handleAppMsg(/** @type {DashMsg} */ (msg), model, deps.cas);
1051
+ return handleAppMsg(msg, model, deps);
265
1052
  }
266
1053
 
267
- /**
268
- * Create the TEA app object for the dashboard.
269
- *
270
- * @param {DashDeps} deps
271
- * @returns {import('@flyingrobots/bijou-tui').App<DashModel, DashMsg>}
272
- */
273
1054
  export function createDashboardApp(deps) {
274
1055
  return {
275
- init: () => /** @type {[DashModel, DashCmd[]]} */ ([createInitModel(), [/** @type {DashCmd} */ (loadEntriesCmd(deps.cas))]]),
276
- update: (/** @type {KeyMsg | ResizeMsg | DashMsg} */ msg, /** @type {DashModel} */ model) => handleUpdate(msg, model, deps),
277
- view: (/** @type {DashModel} */ model) => renderDashboard(model, deps),
1056
+ init: () => [createInitModel(deps.ctx, deps.source), [
1057
+ checkVaultAuthCmd(deps.cas),
1058
+ deps.tick(TITLE_TICK_MS, { type: 'title-tick' }),
1059
+ ]],
1060
+ update: (msg, model) => handleUpdate(msg, model, deps),
1061
+ view: (model) => renderDashboard(model, deps),
278
1062
  };
279
1063
  }
280
1064
 
281
- /**
282
- * Print static list for non-TTY environments.
283
- *
284
- * @param {ContentAddressableStore} cas
285
- */
286
- async function printStaticList(cas) {
287
- const entries = await cas.listVault();
288
- for (const { slug, treeOid } of entries) {
289
- process.stdout.write(`${slug}\t${treeOid}\n`);
1065
+ async function printStaticList(cas, source, output) {
1066
+ const { entries } = await readSourceEntries(cas, source);
1067
+ output.write(formatTabSeparated(entries));
1068
+ }
1069
+
1070
+ function normalizeLaunchContext(ctx) {
1071
+ if (!ctx.mode && !ctx.runtime) {
1072
+ throw new Error('launchDashboard requires ctx.runtime when ctx.mode is absent');
290
1073
  }
1074
+ return ctx;
291
1075
  }
292
1076
 
293
- /**
294
- * Launch the interactive vault dashboard.
295
- *
296
- * @param {ContentAddressableStore} cas
297
- */
298
- export async function launchDashboard(cas) {
299
- if (!process.stdout.isTTY) {
300
- return printStaticList(cas);
1077
+ export async function launchDashboard(cas, options = {}) {
1078
+ const ctx = options.ctx ? normalizeLaunchContext(options.ctx) : createCliTuiContext();
1079
+ const source = options.source ?? { type: 'vault' };
1080
+ if (ctx.mode !== 'interactive') {
1081
+ return printStaticList(cas, source, options.output || process.stdout);
301
1082
  }
302
- const ctx = createNodeContext();
303
- const keyMap = createKeyBindings();
304
- const deps = { keyMap, cas, ctx };
305
- return run(createDashboardApp(deps), { ctx });
1083
+ const dashTick = options.tick || bijouTick;
1084
+ const deps = { cas, ctx, cwdLabel: options.cwd ?? process.cwd(), source, tick: dashTick };
1085
+ const runApp = options.runApp || bijouStartApp;
1086
+ return runApp(createDashboardApp(deps), { ctx });
306
1087
  }
1088
+
1089
+ export { buildTableRows, selectedEntry, selectedManifest, tableSchema };
1090
+ export default launchDashboard;