@git-stunts/git-cas 3.0.0 → 3.1.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,30 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.1.0] — Bijou (2026-02-27)
9
+
10
+ ### Added
11
+ - **Interactive vault dashboard** (`git cas vault dashboard`) — TEA-based TUI with split-pane layout, manifest detail view, keyboard navigation (`j`/`k`/`Enter`/`/`), and real-time filtering.
12
+ - **Manifest inspector** (`git cas inspect <tree-oid>`) — renders manifest details with chunk table, encryption info, and compression badges.
13
+ - **Progress bars** for `store` and `restore` operations — animated progress with throughput reporting, auto-disabled in non-TTY environments.
14
+ - **History timeline** (`git cas vault history --pretty`) — color-coded, paginated timeline view of vault commit history.
15
+ - **Encryption info card** (`git cas vault info --encryption`) — detailed KDF parameters and encryption configuration display.
16
+ - **Chunk heatmap** — chunk-size distribution grid with colored legend, displayed in manifest detail views.
17
+ - `--quiet` / `-q` flag to suppress all progress output.
18
+ - `GIT_CAS_PASSPHRASE` environment variable — alternative to `--vault-passphrase` flag for passphrase-based encryption.
19
+ - New runtime dependencies: `@flyingrobots/bijou`, `@flyingrobots/bijou-node`, `@flyingrobots/bijou-tui`.
20
+
21
+ ### Fixed
22
+ - CLI `restore` now uses the canonical `readManifest` path instead of duplicating manifest resolution logic.
23
+ - Progress trackers wrapped in `try`/`finally` to prevent event listener leaks when `storeFile` or `restoreFile` throws.
24
+ - Dashboard filter and error lines clamped to pane width to prevent wrapping artifacts in narrow terminals.
25
+ - Dashboard differentiates entry vs manifest load errors — a single manifest preload failure no longer sets global error state.
26
+ - Dashboard clamps cursor position after applying filter on entry load.
27
+ - Passphrase resolution uses nullish coalescing for correct falsy-value handling.
28
+ - Locale-agnostic number formatting in encryption card tests.
29
+ - Consolidated duplicated restore flag validation into `validateRestoreFlags()`.
30
+ - Eliminated `vi.mock('node:fs')` pattern in progress tests for Bun Docker compatibility.
31
+
8
32
  ## [3.0.0] — Vault (2026-02-08)
9
33
 
10
34
  ### Added
package/README.md CHANGED
@@ -32,6 +32,8 @@ We use the object database.
32
32
 
33
33
  **Use it for:** binary assets, build artifacts, model weights, data packs, secret bundles, weird experiments, etc.
34
34
 
35
+ <img src="./docs/demo.gif" alt="git-cas demo" />
36
+
35
37
  ## What's new in v2.0.0
36
38
 
37
39
  **Compression** — `compression: { algorithm: 'gzip' }` on `store()`. Compression runs before encryption. Decompression on `restore()` is automatic.
@@ -42,11 +44,15 @@ We use the object database.
42
44
 
43
45
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
44
46
 
45
- ## What's new in v3.0.0
47
+ ## What's new in v3.1.0
48
+
49
+ **Interactive vault dashboard** — `git cas vault dashboard` launches a full TUI with split-pane layout, manifest detail view, keyboard navigation, and real-time filtering. Browse entries, inspect chunks, and view encryption status without memorizing CLI flags.
50
+
51
+ **Progress bars** — `store` and `restore` now show animated progress with throughput reporting. Suppress with `--quiet`.
46
52
 
47
- **Vault** — GC-safe ref-based storage. A single Git ref (`refs/cas/vault`) indexes all stored assets by slug, so `git gc` can no longer silently discard your data. Initialize with `vault init`, store with `--tree`, restore by `--slug`.
53
+ **Pretty history** — `git cas vault history --pretty` renders a color-coded, paginated timeline of vault commits.
48
54
 
49
- **CLI breaking change** — `git cas restore` no longer takes a positional `<tree-oid>` argument. Use `--oid <tree-oid>` or `--slug <slug>` instead.
55
+ **Inspect command** — `git cas inspect <tree-oid>` renders manifest details with chunk table, encryption info, and compression badges.
50
56
 
51
57
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
52
58
 
@@ -122,22 +128,37 @@ git cas vault info my-image
122
128
  git cas vault remove my-image
123
129
  git cas vault history
124
130
 
125
- # Encrypted vault round-trip
126
- git cas vault init --vault-passphrase "secret"
127
- git cas store ./secret.bin --slug vault-entry --tree --vault-passphrase "secret"
128
- git cas restore --slug vault-entry --out ./decrypted.bin --vault-passphrase "secret"
131
+ # Encrypted vault round-trip (passphrase via env var or --vault-passphrase flag)
132
+ export GIT_CAS_PASSPHRASE="secret"
133
+ git cas vault init
134
+ git cas store ./secret.bin --slug vault-entry --tree
135
+ git cas restore --slug vault-entry --out ./decrypted.bin
129
136
  ```
130
137
 
131
- ## Why not Git LFS?
138
+ ## When to use git-cas (and when not to)
139
+
140
+ ### "I just want screenshots in my README"
141
+
142
+ Use an **orphan branch**. Seriously. It's 5 git commands, zero dependencies, and GitHub renders the images inline. Google "git orphan branch assets" — that's all you need. git-cas is overkill for public images and demo GIFs.
143
+
144
+ ### "I need encrypted secrets / large binaries / deduplicated assets in a Git repo"
145
+
146
+ That's git-cas. The orphan branch gives you none of:
147
+
148
+ | | Orphan branch | git-cas |
149
+ |---|---|---|
150
+ | **Encryption** | None — plaintext forever in history | AES-256-GCM + passphrase KDF |
151
+ | **Large files** | Bloats `git clone` for everyone | Chunked, restored on demand |
152
+ | **Dedup** | None | Chunk-level content addressing |
153
+ | **Integrity** | Git SHA-1 | SHA-256 per chunk + GCM auth tag |
154
+ | **Lifecycle** | `git rm` (still in reflog) | Vault with audit trail + `git gc` reclaims |
155
+ | **Compression** | None | gzip before encryption |
132
156
 
133
- Because sometimes you want the Git object database to be the store:
157
+ ### "Why not Git LFS?"
134
158
 
135
- - deterministic
136
- - content-addressed
137
- - locally replicable
138
- - commit-addressable
159
+ Because sometimes you want the Git object database to be the store — deterministic, content-addressed, locally replicable, commit-addressable — with no external server, no LFS endpoint, and no second system to manage.
139
160
 
140
- Also because LFS is, well... LFS.
161
+ If your team uses GitHub and needs file locking + web UI previews, use LFS. If you want encrypted, self-contained, server-free binary storage that travels with `git clone`, use git-cas.
141
162
 
142
163
  ---
143
164
 
package/bin/git-cas.js CHANGED
@@ -5,11 +5,17 @@ import { program } from 'commander';
5
5
  import GitPlumbing, { ShellRunnerFactory } from '@git-stunts/plumbing';
6
6
  import ContentAddressableStore from '../index.js';
7
7
  import Manifest from '../src/domain/value-objects/Manifest.js';
8
+ import { createStoreProgress, createRestoreProgress } from './ui/progress.js';
9
+ import { renderEncryptionCard } from './ui/encryption-card.js';
10
+ import { renderHistoryTimeline } from './ui/history-timeline.js';
11
+ import { renderManifestView } from './ui/manifest-view.js';
12
+ import { renderHeatmap } from './ui/heatmap.js';
8
13
 
9
14
  program
10
15
  .name('git-cas')
11
16
  .description('Content Addressable Storage backed by Git')
12
- .version('3.0.0');
17
+ .version('3.1.0')
18
+ .option('-q, --quiet', 'Suppress progress output');
13
19
 
14
20
  /**
15
21
  * Read a 32-byte raw encryption key from a file.
@@ -45,37 +51,31 @@ async function deriveVaultKey(cas, metadata, passphrase) {
45
51
  }
46
52
 
47
53
  /**
48
- * Resolve encryption key from --key-file or --vault-passphrase.
54
+ * Resolve passphrase from --vault-passphrase flag or GIT_CAS_PASSPHRASE env var.
55
+ */
56
+ function resolvePassphrase(opts) {
57
+ return opts.vaultPassphrase ?? process.env.GIT_CAS_PASSPHRASE;
58
+ }
59
+
60
+ /**
61
+ * Resolve encryption key from --key-file or --vault-passphrase / GIT_CAS_PASSPHRASE.
49
62
  */
50
63
  async function resolveEncryptionKey(cas, opts) {
51
64
  if (opts.keyFile) {
52
65
  return readKeyFile(opts.keyFile);
53
66
  }
54
- if (!opts.vaultPassphrase) {
67
+ const passphrase = resolvePassphrase(opts);
68
+ if (!passphrase) {
55
69
  return undefined;
56
70
  }
57
71
  const metadata = await cas.getVaultMetadata();
58
72
  if (metadata?.encryption) {
59
- return deriveVaultKey(cas, metadata, opts.vaultPassphrase);
73
+ return deriveVaultKey(cas, metadata, passphrase);
60
74
  }
61
- process.stderr.write('warning: --vault-passphrase ignored (vault is not encrypted)\n');
75
+ process.stderr.write('warning: passphrase ignored (vault is not encrypted)\n');
62
76
  return undefined;
63
77
  }
64
78
 
65
- /**
66
- * Read the manifest from a tree OID.
67
- */
68
- async function readManifestFromTree(service, treeOid) {
69
- const entries = await service.persistence.readTree(treeOid);
70
- const entry = entries.find((e) => e.name.startsWith('manifest.'));
71
- if (!entry) {
72
- process.stderr.write('error: No manifest found in tree\n');
73
- process.exit(1);
74
- }
75
- const blob = await service.persistence.readBlob(entry.oid);
76
- return new Manifest(service.codec.decode(blob));
77
- }
78
-
79
79
  /**
80
80
  * Validate --slug / --oid flags (exactly one required).
81
81
  */
@@ -100,7 +100,7 @@ program
100
100
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
101
101
  .option('--tree', 'Also create a Git tree and print its OID')
102
102
  .option('--force', 'Overwrite existing vault entry')
103
- .option('--vault-passphrase <pass>', 'Vault-level passphrase for encryption')
103
+ .option('--vault-passphrase <pass>', 'Vault-level passphrase for encryption (prefer GIT_CAS_PASSPHRASE env var)')
104
104
  .option('--cwd <dir>', 'Git working directory', '.')
105
105
  .action(async (file, opts) => {
106
106
  try {
@@ -111,7 +111,17 @@ program
111
111
  storeOpts.encryptionKey = encryptionKey;
112
112
  }
113
113
 
114
- const manifest = await cas.storeFile(storeOpts);
114
+ const service = await cas.getService();
115
+ const progress = createStoreProgress({
116
+ filePath: file, chunkSize: cas.chunkSize, quiet: program.opts().quiet,
117
+ });
118
+ progress.attach(service);
119
+ let manifest;
120
+ try {
121
+ manifest = await cas.storeFile(storeOpts);
122
+ } finally {
123
+ progress.detach();
124
+ }
115
125
 
116
126
  if (opts.tree) {
117
127
  const treeOid = await cas.createTree({ manifest });
@@ -147,6 +157,36 @@ program
147
157
  }
148
158
  });
149
159
 
160
+ // ---------------------------------------------------------------------------
161
+ // inspect
162
+ // ---------------------------------------------------------------------------
163
+ program
164
+ .command('inspect')
165
+ .description('Inspect a stored manifest')
166
+ .option('--slug <slug>', 'Resolve tree OID from vault slug')
167
+ .option('--oid <tree-oid>', 'Direct tree OID')
168
+ .option('--heatmap', 'Show chunk heatmap visualization')
169
+ .option('--cwd <dir>', 'Git working directory', '.')
170
+ .action(async (opts) => {
171
+ try {
172
+ validateRestoreFlags(opts);
173
+ const cas = createCas(opts.cwd);
174
+ const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
175
+ const manifest = await cas.readManifest({ treeOid });
176
+
177
+ if (opts.heatmap) {
178
+ process.stdout.write(renderHeatmap({ manifest }));
179
+ } else if (process.stdout.isTTY) {
180
+ process.stdout.write(renderManifestView({ manifest }));
181
+ } else {
182
+ process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
183
+ }
184
+ } catch (err) {
185
+ process.stderr.write(`error: ${err.message}\n`);
186
+ process.exit(1);
187
+ }
188
+ });
189
+
150
190
  // ---------------------------------------------------------------------------
151
191
  // restore
152
192
  // ---------------------------------------------------------------------------
@@ -157,15 +197,14 @@ program
157
197
  .option('--slug <slug>', 'Resolve tree OID from vault slug')
158
198
  .option('--oid <tree-oid>', 'Direct tree OID')
159
199
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
160
- .option('--vault-passphrase <pass>', 'Vault-level passphrase for decryption')
200
+ .option('--vault-passphrase <pass>', 'Vault-level passphrase for decryption (prefer GIT_CAS_PASSPHRASE env var)')
161
201
  .option('--cwd <dir>', 'Git working directory', '.')
162
202
  .action(async (opts) => {
163
203
  try {
164
204
  validateRestoreFlags(opts);
165
205
  const cas = createCas(opts.cwd);
166
206
  const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
167
- const service = await cas.getService();
168
- const manifest = await readManifestFromTree(service, treeOid);
207
+ const manifest = await cas.readManifest({ treeOid });
169
208
 
170
209
  const restoreOpts = { manifest };
171
210
  const encryptionKey = await resolveEncryptionKey(cas, opts);
@@ -173,10 +212,20 @@ program
173
212
  restoreOpts.encryptionKey = encryptionKey;
174
213
  }
175
214
 
176
- const { bytesWritten } = await cas.restoreFile({
177
- ...restoreOpts,
178
- outputPath: opts.out,
215
+ const service = await cas.getService();
216
+ const progress = createRestoreProgress({
217
+ totalChunks: manifest.chunks.length, quiet: program.opts().quiet,
179
218
  });
219
+ progress.attach(service);
220
+ let bytesWritten;
221
+ try {
222
+ ({ bytesWritten } = await cas.restoreFile({
223
+ ...restoreOpts,
224
+ outputPath: opts.out,
225
+ }));
226
+ } finally {
227
+ progress.detach();
228
+ }
180
229
  process.stdout.write(`${bytesWritten}\n`);
181
230
  } catch (err) {
182
231
  process.stderr.write(`error: ${err.message}\n`);
@@ -194,15 +243,16 @@ const vault = program
194
243
  vault
195
244
  .command('init')
196
245
  .description('Initialize the vault')
197
- .option('--vault-passphrase <pass>', 'Passphrase for vault-level encryption')
246
+ .option('--vault-passphrase <pass>', 'Passphrase for vault-level encryption (prefer GIT_CAS_PASSPHRASE env var)')
198
247
  .option('--algorithm <alg>', 'KDF algorithm (pbkdf2 or scrypt)', 'pbkdf2')
199
248
  .option('--cwd <dir>', 'Git working directory', '.')
200
249
  .action(async (opts) => {
201
250
  try {
202
251
  const cas = createCas(opts.cwd);
203
252
  const initOpts = {};
204
- if (opts.vaultPassphrase) {
205
- initOpts.passphrase = opts.vaultPassphrase;
253
+ const passphrase = resolvePassphrase(opts);
254
+ if (passphrase) {
255
+ initOpts.passphrase = passphrase;
206
256
  initOpts.kdfOptions = { algorithm: opts.algorithm };
207
257
  }
208
258
  const { commitOid } = await cas.initVault(initOpts);
@@ -257,6 +307,7 @@ vault
257
307
  vault
258
308
  .command('info <slug>')
259
309
  .description('Show info for a vault entry')
310
+ .option('--encryption', 'Show vault encryption details')
260
311
  .option('--cwd <dir>', 'Git working directory', '.')
261
312
  .action(async (slug, opts) => {
262
313
  try {
@@ -264,6 +315,10 @@ vault
264
315
  const treeOid = await cas.resolveVaultEntry({ slug });
265
316
  process.stdout.write(`slug\t${slug}\n`);
266
317
  process.stdout.write(`tree\t${treeOid}\n`);
318
+ if (opts.encryption) {
319
+ const metadata = await cas.getVaultMetadata();
320
+ process.stdout.write(`\n${renderEncryptionCard({ metadata })}\n`);
321
+ }
267
322
  } catch (err) {
268
323
  process.stderr.write(`error: ${err.message}\n`);
269
324
  process.exit(1);
@@ -278,6 +333,7 @@ vault
278
333
  .description('Show vault commit history')
279
334
  .option('--cwd <dir>', 'Git working directory', '.')
280
335
  .option('-n, --max-count <n>', 'Limit number of commits')
336
+ .option('--pretty', 'Render as color-coded timeline')
281
337
  .action(async (opts) => {
282
338
  try {
283
339
  const runner = ShellRunnerFactory.create();
@@ -292,7 +348,29 @@ vault
292
348
  args.push(`-${n}`);
293
349
  }
294
350
  const output = await plumbing.execute({ args });
295
- process.stdout.write(`${output}\n`);
351
+ if (opts.pretty && process.stdout.isTTY) {
352
+ process.stdout.write(`${renderHistoryTimeline(output)}\n`);
353
+ } else {
354
+ process.stdout.write(`${output}\n`);
355
+ }
356
+ } catch (err) {
357
+ process.stderr.write(`error: ${err.message}\n`);
358
+ process.exit(1);
359
+ }
360
+ });
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // vault dashboard
364
+ // ---------------------------------------------------------------------------
365
+ vault
366
+ .command('dashboard')
367
+ .description('Interactive vault explorer')
368
+ .option('--cwd <dir>', 'Git working directory', '.')
369
+ .action(async (opts) => {
370
+ try {
371
+ const cas = createCas(opts.cwd);
372
+ const { launchDashboard } = await import('./ui/dashboard.js');
373
+ await launchDashboard(cas);
296
374
  } catch (err) {
297
375
  process.stderr.write(`error: ${err.message}\n`);
298
376
  process.exit(1);
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Shared bijou context configured for CLI use (writes to stderr).
3
+ */
4
+
5
+ import { createBijou } from '@flyingrobots/bijou';
6
+ import { nodeRuntime, chalkStyle } from '@flyingrobots/bijou-node';
7
+
8
+ let ctx = null;
9
+
10
+ /**
11
+ * Returns a bijou context that writes to stderr instead of stdout.
12
+ * Stdout is reserved for structured output (OIDs, JSON).
13
+ */
14
+ export function getCliContext() {
15
+ if (ctx) {
16
+ return ctx;
17
+ }
18
+ const runtime = nodeRuntime();
19
+ const noColor = runtime.env('NO_COLOR') !== undefined;
20
+ ctx = createBijou({
21
+ runtime,
22
+ io: stderrIO(),
23
+ style: chalkStyle(noColor),
24
+ });
25
+ return ctx;
26
+ }
27
+
28
+ function stderrIO() {
29
+ return {
30
+ write(data) {
31
+ process.stderr.write(data);
32
+ },
33
+ question() {
34
+ throw new Error('question() not supported in CLI context');
35
+ },
36
+ rawInput() {
37
+ throw new Error('rawInput() not supported in CLI context');
38
+ },
39
+ onResize(callback) {
40
+ const handler = () => {
41
+ callback(process.stderr.columns ?? 80, process.stderr.rows ?? 24);
42
+ };
43
+ process.stderr.on('resize', handler);
44
+ return { dispose() { process.stderr.removeListener('resize', handler); } };
45
+ },
46
+ setInterval(callback, ms) {
47
+ const id = globalThis.setInterval(callback, ms);
48
+ return { dispose() { globalThis.clearInterval(id); } };
49
+ },
50
+ readFile() { throw new Error('readFile() not supported'); },
51
+ readDir() { throw new Error('readDir() not supported'); },
52
+ joinPath(...segments) { return segments.join('/'); },
53
+ };
54
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Async command factories for the vault dashboard.
3
+ */
4
+
5
+ /**
6
+ * Load vault entries and metadata in parallel.
7
+ */
8
+ export function loadEntriesCmd(cas) {
9
+ return async () => {
10
+ try {
11
+ const [entries, metadata] = await Promise.all([
12
+ cas.listVault(),
13
+ cas.getVaultMetadata(),
14
+ ]);
15
+ return { type: 'loaded-entries', entries, metadata };
16
+ } catch (err) {
17
+ return { type: 'load-error', source: 'entries', error: err.message };
18
+ }
19
+ };
20
+ }
21
+
22
+ /**
23
+ * Load a single manifest by slug and tree OID.
24
+ */
25
+ export function loadManifestCmd(cas, slug, treeOid) {
26
+ return async () => {
27
+ try {
28
+ const manifest = await cas.readManifest({ treeOid });
29
+ return { type: 'loaded-manifest', slug, manifest };
30
+ } catch (err) {
31
+ return { type: 'load-error', source: 'manifest', slug, error: err.message };
32
+ }
33
+ };
34
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Pure render functions for the vault dashboard.
3
+ */
4
+
5
+ import { badge } from '@flyingrobots/bijou';
6
+ import { flex, viewport } from '@flyingrobots/bijou-tui';
7
+ import { renderManifestView } from './manifest-view.js';
8
+
9
+ /**
10
+ * Format bytes as compact string.
11
+ */
12
+ function formatSize(bytes) {
13
+ if (bytes < 1024) { return `${bytes}B`; }
14
+ if (bytes < 1024 * 1024) { return `${(bytes / 1024).toFixed(1)}K`; }
15
+ if (bytes < 1024 * 1024 * 1024) { return `${(bytes / (1024 * 1024)).toFixed(1)}M`; }
16
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}G`;
17
+ }
18
+
19
+ /**
20
+ * Format manifest stats for the list.
21
+ */
22
+ function formatStats(manifest) {
23
+ const m = manifest.toJSON ? manifest.toJSON() : manifest;
24
+ return `${formatSize(m.size)} ${m.chunks?.length ?? 0}c`;
25
+ }
26
+
27
+ /**
28
+ * Render a single list item.
29
+ */
30
+ function renderListItem(entry, index, opts) {
31
+ const prefix = index === opts.model.cursor ? '> ' : ' ';
32
+ const manifest = opts.model.manifestCache.get(entry.slug);
33
+ const stats = manifest ? formatStats(manifest) : '...';
34
+ const line = `${prefix}${entry.slug} ${stats}`;
35
+ return opts.width ? line.slice(0, opts.width) : line;
36
+ }
37
+
38
+ /**
39
+ * Compute visible window for cursor scrolling.
40
+ */
41
+ function visibleRange(cursor, total, height) {
42
+ const start = Math.max(0, Math.min(cursor - Math.floor(height / 2), total - height));
43
+ return { start: Math.max(0, start), end: Math.min(Math.max(0, start) + height, total) };
44
+ }
45
+
46
+ /**
47
+ * Render the header line.
48
+ */
49
+ function renderHeader(model, ctx) {
50
+ const parts = [];
51
+ if (model.metadata?.encryption) {
52
+ parts.push(badge('encrypted', { variant: 'warning', ctx }));
53
+ }
54
+ parts.push(`${model.entries.length} entries`);
55
+ parts.push('refs/cas/vault');
56
+ return parts.join(' ');
57
+ }
58
+
59
+ /**
60
+ * Render the list pane.
61
+ */
62
+ function renderListPane(model, size) {
63
+ const clamp = (s) => (size.width ? s.slice(0, size.width) : s);
64
+ const filterLine = model.filtering ? clamp(`/${model.filterText}\u2588`) : '';
65
+ const listHeight = model.filtering ? size.height - 1 : size.height;
66
+ const items = model.filtered;
67
+
68
+ if (items.length === 0) {
69
+ const msg = clamp(
70
+ model.status === 'loading'
71
+ ? 'Loading...'
72
+ : model.error
73
+ ? `Error: ${model.error}`
74
+ : 'No entries',
75
+ );
76
+ return padToHeight(msg, listHeight, filterLine);
77
+ }
78
+
79
+ const { start, end } = visibleRange(model.cursor, items.length, listHeight);
80
+ const lines = [];
81
+ for (let i = start; i < end; i++) {
82
+ lines.push(renderListItem(items[i], i, { model, width: size.width }));
83
+ }
84
+ return padToHeight(lines.join('\n'), listHeight, filterLine);
85
+ }
86
+
87
+ /**
88
+ * Pad content to target height, optionally appending a suffix line.
89
+ */
90
+ function padToHeight(content, height, suffix) {
91
+ const lines = content.split('\n');
92
+ while (lines.length < height) { lines.push(''); }
93
+ return suffix ? `${lines.join('\n')}\n${suffix}` : lines.join('\n');
94
+ }
95
+
96
+ /**
97
+ * Render the detail pane with viewport scrolling.
98
+ */
99
+ function renderDetailPane(model, opts) {
100
+ const entry = model.filtered[model.cursor];
101
+ if (!entry) { return ''; }
102
+ const manifest = model.manifestCache.get(entry.slug);
103
+ if (!manifest) { return 'Loading manifest...'; }
104
+ const content = renderManifestView({ manifest, ctx: opts.ctx });
105
+ return viewport({ width: opts.width, height: opts.height, content, scrollY: model.detailScroll });
106
+ }
107
+
108
+ /**
109
+ * Render the body with list and detail panes.
110
+ */
111
+ function renderBody(model, deps, size) {
112
+ const listBasis = Math.floor(size.width * 0.35);
113
+ return flex(
114
+ { direction: 'row', width: size.width, height: size.height, gap: 1 },
115
+ { content: (w, h) => renderListPane(model, { height: h, width: w }), basis: listBasis },
116
+ { content: (w, h) => renderDetailPane(model, { width: w, height: h, ctx: deps.ctx }), flex: 1 },
117
+ );
118
+ }
119
+
120
+ /**
121
+ * Render the full dashboard layout.
122
+ */
123
+ export function renderDashboard(model, deps) {
124
+ return flex(
125
+ { direction: 'column', width: model.columns, height: model.rows },
126
+ { content: renderHeader(model, deps.ctx), basis: 1 },
127
+ { content: (w, _h) => '\u2500'.repeat(w), basis: 1 },
128
+ { content: (w, h) => renderBody(model, deps, { width: w, height: h }), flex: 1 },
129
+ { content: (w, _h) => '\u2500'.repeat(w), basis: 1 },
130
+ { content: 'j/k Navigate enter Load / Filter J/K Scroll q Quit', basis: 1 },
131
+ );
132
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * TEA app shell for the vault dashboard.
3
+ */
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';
9
+
10
+ /**
11
+ * Create keyboard bindings for normal mode.
12
+ */
13
+ export function createKeyBindings() {
14
+ return createKeyMap()
15
+ .bind('q', 'Quit', { type: 'quit' })
16
+ .bind('j', 'Down', { type: 'move', delta: 1 })
17
+ .bind('down', 'Down', { type: 'move', delta: 1 })
18
+ .bind('k', 'Up', { type: 'move', delta: -1 })
19
+ .bind('up', 'Up', { type: 'move', delta: -1 })
20
+ .bind('enter', 'Load', { type: 'select' })
21
+ .bind('/', 'Filter', { type: 'filter-start' })
22
+ .bind('shift+j', 'Scroll down', { type: 'scroll-detail', delta: 3 })
23
+ .bind('shift+k', 'Scroll up', { type: 'scroll-detail', delta: -3 });
24
+ }
25
+
26
+ /**
27
+ * Create the initial model.
28
+ */
29
+ function createInitModel() {
30
+ return {
31
+ status: 'loading',
32
+ columns: process.stdout.columns ?? 80,
33
+ rows: process.stdout.rows ?? 24,
34
+ entries: [],
35
+ filtered: [],
36
+ cursor: 0,
37
+ filterText: '',
38
+ filtering: false,
39
+ metadata: null,
40
+ manifestCache: new Map(),
41
+ loadingSlug: null,
42
+ detailScroll: 0,
43
+ error: null,
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Apply filter text to entries.
49
+ */
50
+ function applyFilter(entries, text) {
51
+ if (!text) { return entries; }
52
+ return entries.filter(e => e.slug.includes(text));
53
+ }
54
+
55
+ /**
56
+ * Handle the loaded-entries message.
57
+ */
58
+ function handleLoadedEntries(msg, model, cas) {
59
+ const filtered = applyFilter(msg.entries, model.filterText);
60
+ const cursor = Math.max(0, Math.min(model.cursor, filtered.length - 1));
61
+ const cmds = msg.entries.map(e => loadManifestCmd(cas, e.slug, e.treeOid));
62
+ return [{
63
+ ...model,
64
+ status: 'ready',
65
+ entries: msg.entries,
66
+ filtered,
67
+ cursor,
68
+ metadata: msg.metadata,
69
+ }, cmds];
70
+ }
71
+
72
+ /**
73
+ * Handle a loaded-manifest message.
74
+ */
75
+ function handleLoadedManifest(msg, model) {
76
+ const cache = new Map(model.manifestCache);
77
+ cache.set(msg.slug, msg.manifest);
78
+ return [{ ...model, manifestCache: cache }, []];
79
+ }
80
+
81
+ /**
82
+ * Handle cursor movement.
83
+ */
84
+ function handleMove(msg, model) {
85
+ const max = model.filtered.length - 1;
86
+ const cursor = Math.max(0, Math.min(max, model.cursor + msg.delta));
87
+ return [{ ...model, cursor, detailScroll: 0 }, []];
88
+ }
89
+
90
+ /**
91
+ * Handle filter key input in filter mode.
92
+ */
93
+ function handleFilterKey(msg, model) {
94
+ if (msg.key === 'escape' || msg.key === 'enter') {
95
+ return [{ ...model, filtering: false }, []];
96
+ }
97
+ if (msg.key === 'backspace') {
98
+ const text = model.filterText.slice(0, -1);
99
+ const filtered = applyFilter(model.entries, text);
100
+ return [{ ...model, filterText: text, filtered, cursor: 0 }, []];
101
+ }
102
+ if (msg.key.length === 1) {
103
+ const text = model.filterText + msg.key;
104
+ const filtered = applyFilter(model.entries, text);
105
+ return [{ ...model, filterText: text, filtered, cursor: 0 }, []];
106
+ }
107
+ return [model, []];
108
+ }
109
+
110
+ /**
111
+ * Handle select (enter key) to load manifest.
112
+ */
113
+ function handleSelect(model, deps) {
114
+ const entry = model.filtered[model.cursor];
115
+ if (!entry || model.manifestCache.has(entry.slug)) {
116
+ return [model, []];
117
+ }
118
+ const cmd = loadManifestCmd(deps.cas, entry.slug, entry.treeOid);
119
+ return [{ ...model, loadingSlug: entry.slug }, [cmd]];
120
+ }
121
+
122
+ /**
123
+ * Handle keymap actions.
124
+ */
125
+ function handleAction(action, model, deps) {
126
+ if (action.type === 'quit') { return [model, [quit()]]; }
127
+ if (action.type === 'move') { return handleMove(action, model); }
128
+ if (action.type === 'filter-start') {
129
+ return [{ ...model, filtering: true, filterText: '', filtered: model.entries, cursor: 0 }, []];
130
+ }
131
+ if (action.type === 'scroll-detail') {
132
+ const scroll = Math.max(0, model.detailScroll + action.delta);
133
+ return [{ ...model, detailScroll: scroll }, []];
134
+ }
135
+ if (action.type === 'select') { return handleSelect(model, deps); }
136
+ return [model, []];
137
+ }
138
+
139
+ /**
140
+ * Handle app-level messages (data loading results).
141
+ */
142
+ function handleAppMsg(msg, model, cas) {
143
+ if (msg.type === 'loaded-entries') { return handleLoadedEntries(msg, model, cas); }
144
+ if (msg.type === 'loaded-manifest') { return handleLoadedManifest(msg, model); }
145
+ if (msg.type === 'load-error') {
146
+ if (msg.source === 'manifest') {
147
+ return [model, []];
148
+ }
149
+ return [{ ...model, status: 'error', error: msg.error }, []];
150
+ }
151
+ return [model, []];
152
+ }
153
+
154
+ /**
155
+ * Route all update messages to the appropriate handler.
156
+ */
157
+ function handleUpdate(msg, model, deps) {
158
+ if (msg.type === 'key' && model.filtering) {
159
+ return handleFilterKey(msg, model);
160
+ }
161
+ if (msg.type === 'key') {
162
+ const action = deps.keyMap.handle(msg);
163
+ if (action) { return handleAction(action, model, deps); }
164
+ return [model, []];
165
+ }
166
+ if (msg.type === 'resize') {
167
+ return [{ ...model, columns: msg.columns, rows: msg.rows }, []];
168
+ }
169
+ return handleAppMsg(msg, model, deps.cas);
170
+ }
171
+
172
+ /**
173
+ * Create the TEA app object for the dashboard.
174
+ */
175
+ export function createDashboardApp(deps) {
176
+ return {
177
+ init: () => [createInitModel(), [loadEntriesCmd(deps.cas)]],
178
+ update: (msg, model) => handleUpdate(msg, model, deps),
179
+ view: (model) => renderDashboard(model, deps),
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Print static list for non-TTY environments.
185
+ */
186
+ async function printStaticList(cas) {
187
+ const entries = await cas.listVault();
188
+ for (const { slug, treeOid } of entries) {
189
+ process.stdout.write(`${slug}\t${treeOid}\n`);
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Launch the interactive vault dashboard.
195
+ */
196
+ export async function launchDashboard(cas) {
197
+ if (!process.stdout.isTTY) {
198
+ return printStaticList(cas);
199
+ }
200
+ const ctx = createNodeContext();
201
+ const keyMap = createKeyBindings();
202
+ const deps = { keyMap, cas, ctx };
203
+ return run(createDashboardApp(deps), { ctx });
204
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Encryption info card — visual summary of vault crypto configuration.
3
+ */
4
+
5
+ import { box, badge, headerBox } from '@flyingrobots/bijou';
6
+ import { getCliContext } from './context.js';
7
+
8
+ /**
9
+ * Render an encryption info card for the vault.
10
+ *
11
+ * @param {Object} options
12
+ * @param {Object|null} options.metadata - Vault metadata (from getVaultMetadata()).
13
+ * @param {boolean} [options.unlocked] - Whether a key/passphrase was provided.
14
+ * @returns {string}
15
+ */
16
+ export function renderEncryptionCard({ metadata, unlocked = false }) {
17
+ const ctx = getCliContext();
18
+
19
+ if (!metadata?.encryption) {
20
+ return box('No encryption configured', { ctx });
21
+ }
22
+
23
+ const { encryption } = metadata;
24
+ const { kdf } = encryption;
25
+
26
+ const status = unlocked
27
+ ? badge('unlocked', { variant: 'success', ctx })
28
+ : badge('locked', { variant: 'error', ctx });
29
+
30
+ const rows = [
31
+ ` cipher ${encryption.cipher}`,
32
+ ` kdf ${kdf.algorithm}`,
33
+ ];
34
+
35
+ if (kdf.algorithm === 'pbkdf2') {
36
+ rows.push(` iterations ${kdf.iterations.toLocaleString()}`);
37
+ } else if (kdf.algorithm === 'scrypt') {
38
+ rows.push(` cost ${kdf.cost}`);
39
+ rows.push(` blockSize ${kdf.blockSize}`);
40
+ rows.push(` parallel ${kdf.parallelization}`);
41
+ }
42
+
43
+ rows.push(` key length ${kdf.keyLength} bytes`);
44
+ rows.push(` salt ${kdf.salt.slice(0, 12)}...`);
45
+ rows.push(` status ${status}`);
46
+
47
+ const content = rows.join('\n');
48
+ return `${headerBox('Encryption', { ctx })}\n${box(content, { ctx })}`;
49
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Chunk heatmap visualization — visual block map of chunks.
3
+ */
4
+
5
+ import { gradientText } from '@flyingrobots/bijou';
6
+ import { getCliContext } from './context.js';
7
+
8
+ const GRADIENT_STOPS = [
9
+ { pos: 0, color: [0, 255, 255] },
10
+ { pos: 1, color: [255, 0, 255] },
11
+ ];
12
+
13
+ /**
14
+ * Format bytes as human-readable string.
15
+ */
16
+ function formatBytes(bytes) {
17
+ if (bytes < 1024) {
18
+ return `${bytes} B`;
19
+ }
20
+ if (bytes < 1024 * 1024) {
21
+ return `${(bytes / 1024).toFixed(1)} KiB`;
22
+ }
23
+ if (bytes < 1024 * 1024 * 1024) {
24
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
25
+ }
26
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
27
+ }
28
+
29
+ /**
30
+ * Build the block grid string from chunks.
31
+ */
32
+ function buildGrid(chunks, boundaries, width) {
33
+ let grid = '';
34
+ let col = 0;
35
+
36
+ for (let i = 0; i < chunks.length; i++) {
37
+ if (boundaries.has(i) && col > 0) {
38
+ grid += '\n';
39
+ col = 0;
40
+ }
41
+
42
+ grid += '\u2588';
43
+ col++;
44
+
45
+ if (col >= width) {
46
+ grid += '\n';
47
+ col = 0;
48
+ }
49
+ }
50
+
51
+ if (col > 0) {
52
+ grid += '\n';
53
+ }
54
+ return grid;
55
+ }
56
+
57
+ /**
58
+ * Build the legend line.
59
+ */
60
+ function buildLegend(chunks, subManifests) {
61
+ const chunkSize = chunks.length > 0 ? chunks[0].size : 0;
62
+ const parts = [`${chunks.length} chunks`];
63
+ if (subManifests.length) {
64
+ parts.push(`${subManifests.length} sub-manifests`);
65
+ }
66
+ if (chunkSize) {
67
+ parts.push(`${formatBytes(chunkSize)}/chunk`);
68
+ }
69
+ return parts.join(' ');
70
+ }
71
+
72
+ /**
73
+ * Render a chunk heatmap for a manifest.
74
+ *
75
+ * @param {Object} options
76
+ * @param {Object} options.manifest - The manifest (from readManifest).
77
+ * @returns {string}
78
+ */
79
+ export function renderHeatmap({ manifest }) {
80
+ const ctx = getCliContext();
81
+ const m = manifest.toJSON ? manifest.toJSON() : manifest;
82
+ const chunks = m.chunks || [];
83
+
84
+ if (chunks.length === 0) {
85
+ return 'No chunks to display\n';
86
+ }
87
+
88
+ const width = Math.min(60, (ctx.runtime.columns || 80) - 10);
89
+ const subManifests = m.subManifests || [];
90
+
91
+ const boundaries = new Set();
92
+ for (const sm of subManifests) {
93
+ if (sm.startIndex > 0) {
94
+ boundaries.add(sm.startIndex);
95
+ }
96
+ }
97
+
98
+ const grid = buildGrid(chunks, boundaries, width);
99
+ const colored = gradientText(grid, GRADIENT_STOPS, { style: ctx.style });
100
+ const legend = buildLegend(chunks, subManifests);
101
+
102
+ return `${colored}\n${legend}\n`;
103
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Vault history as a color-coded timeline.
3
+ */
4
+
5
+ import { timeline, paginator } from '@flyingrobots/bijou';
6
+ import { getCliContext } from './context.js';
7
+
8
+ /**
9
+ * Parse a vault commit line into structured data.
10
+ * Input format: "eff5569 vault: add photos/beach"
11
+ *
12
+ * @param {string} line
13
+ * @returns {{ oid: string, operation: string, slug: string|null }|null}
14
+ */
15
+ function parseCommitLine(line) {
16
+ const trimmed = line.trim();
17
+ if (!trimmed) {
18
+ return null;
19
+ }
20
+
21
+ const spaceIdx = trimmed.indexOf(' ');
22
+ if (spaceIdx === -1) {
23
+ return null;
24
+ }
25
+
26
+ const oid = trimmed.slice(0, spaceIdx);
27
+ const message = trimmed.slice(spaceIdx + 1);
28
+
29
+ const match = message.match(/^vault:\s*(init|add|update|remove)\s*(.*)$/);
30
+ if (!match) {
31
+ return { oid, operation: 'unknown', slug: message };
32
+ }
33
+
34
+ return { oid, operation: match[1], slug: match[2] || null };
35
+ }
36
+
37
+ const STATUS_MAP = {
38
+ init: 'info',
39
+ add: 'success',
40
+ update: 'warning',
41
+ remove: 'error',
42
+ unknown: 'pending',
43
+ };
44
+
45
+ /**
46
+ * Render vault history as a color-coded timeline.
47
+ *
48
+ * @param {string} gitLogOutput - Raw output from `git log --oneline`.
49
+ * @param {Object} [options]
50
+ * @param {number} [options.page] - Current page (1-based).
51
+ * @param {number} [options.perPage] - Entries per page (default 20).
52
+ * @returns {string}
53
+ */
54
+ export function renderHistoryTimeline(gitLogOutput, options = {}) {
55
+ const ctx = getCliContext();
56
+ const perPage = options.perPage ?? 20;
57
+ const page = options.page ?? 1;
58
+
59
+ const lines = gitLogOutput.split('\n').filter(Boolean);
60
+ if (lines.length === 0) {
61
+ return 'No history\n';
62
+ }
63
+
64
+ const totalPages = Math.ceil(lines.length / perPage);
65
+ const start = (page - 1) * perPage;
66
+ const pageLines = lines.slice(start, start + perPage);
67
+
68
+ const events = pageLines
69
+ .map(parseCommitLine)
70
+ .filter(Boolean)
71
+ .map(({ oid, operation, slug }) => ({
72
+ label: slug ? `vault: ${operation} ${slug}` : `vault: ${operation}`,
73
+ description: oid,
74
+ status: STATUS_MAP[operation] || 'pending',
75
+ }));
76
+
77
+ let output = timeline(events, { ctx });
78
+
79
+ if (totalPages > 1) {
80
+ output += `\n${paginator({ current: page, total: totalPages, ctx })}`;
81
+ }
82
+
83
+ return output;
84
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Manifest anatomy view — rich visual breakdown of a manifest.
3
+ */
4
+
5
+ import { box, badge, table, tree, headerBox } from '@flyingrobots/bijou';
6
+ import { getCliContext } from './context.js';
7
+
8
+ /**
9
+ * Format bytes as human-readable string.
10
+ */
11
+ function formatBytes(bytes) {
12
+ if (bytes < 1024) {
13
+ return `${bytes} B`;
14
+ }
15
+ if (bytes < 1024 * 1024) {
16
+ return `${(bytes / 1024).toFixed(1)} KiB`;
17
+ }
18
+ if (bytes < 1024 * 1024 * 1024) {
19
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
20
+ }
21
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
22
+ }
23
+
24
+ /**
25
+ * Build the header badges line.
26
+ */
27
+ function renderBadges(m, ctx) {
28
+ const badges = [badge(`v${m.version}`, { ctx })];
29
+ if (m.encryption) {
30
+ badges.push(badge('encrypted', { variant: 'warning', ctx }));
31
+ }
32
+ if (m.compression) {
33
+ badges.push(badge(m.compression.algorithm, { variant: 'info', ctx }));
34
+ }
35
+ if (m.subManifests?.length) {
36
+ badges.push(badge('merkle', { variant: 'info', ctx }));
37
+ }
38
+ return badges.join(' ');
39
+ }
40
+
41
+ /**
42
+ * Build the encryption section.
43
+ */
44
+ function renderEncryptionSection(enc, ctx) {
45
+ const rows = [` algorithm ${enc.algorithm}`];
46
+ if (enc.kdf) {
47
+ rows.push(` kdf ${enc.kdf.algorithm}`);
48
+ if (enc.kdf.iterations) {
49
+ rows.push(` iterations ${enc.kdf.iterations.toLocaleString()}`);
50
+ }
51
+ if (enc.kdf.cost) {
52
+ rows.push(` cost ${enc.kdf.cost}`);
53
+ }
54
+ }
55
+ if (enc.nonce) {
56
+ rows.push(` nonce ${enc.nonce.slice(0, 16)}...`);
57
+ }
58
+ if (enc.tag) {
59
+ rows.push(` tag ${enc.tag.slice(0, 16)}...`);
60
+ }
61
+ return `${headerBox('Encryption', { ctx })}\n${box(rows.join('\n'), { ctx })}`;
62
+ }
63
+
64
+ /**
65
+ * Build the chunks section.
66
+ */
67
+ function renderChunksSection(chunks, ctx) {
68
+ const displayChunks = chunks.slice(0, 20);
69
+ const chunkRows = displayChunks.map(c => [
70
+ String(c.index),
71
+ formatBytes(c.size),
72
+ `${c.digest.slice(0, 12)}...`,
73
+ `${c.blob.slice(0, 12)}...`,
74
+ ]);
75
+ const chunkTable = table({
76
+ columns: [{ header: '#' }, { header: 'Size' }, { header: 'Digest' }, { header: 'Blob' }],
77
+ rows: chunkRows,
78
+ ctx,
79
+ });
80
+ const suffix = chunks.length > 20
81
+ ? `\n ...and ${chunks.length - 20} more`
82
+ : '';
83
+ return `${headerBox(`Chunks (${chunks.length})`, { ctx })}\n${chunkTable}${suffix}`;
84
+ }
85
+
86
+ /**
87
+ * Build the metadata section.
88
+ */
89
+ function renderMetadataSection(m, ctx) {
90
+ const meta = [
91
+ ` slug ${m.slug}`,
92
+ ` filename ${m.filename}`,
93
+ ` size ${formatBytes(m.size)}`,
94
+ ` chunks ${m.chunks?.length ?? 0}`,
95
+ ];
96
+ return `${headerBox('Metadata', { ctx })}\n${box(meta.join('\n'), { ctx })}`;
97
+ }
98
+
99
+ /**
100
+ * Build the sub-manifests section.
101
+ */
102
+ function renderSubManifestsSection(m, ctx) {
103
+ const nodes = m.subManifests.map((sm, i) => ({
104
+ label: `sub-${i} ${sm.chunkCount} chunks start: ${sm.startIndex} oid: ${sm.oid.slice(0, 8)}...`,
105
+ }));
106
+ return `${headerBox(`Sub-manifests (${m.subManifests.length})`, { ctx })}\n${tree(nodes, { ctx })}`;
107
+ }
108
+
109
+ /**
110
+ * Render a full manifest anatomy view.
111
+ *
112
+ * @param {Object} options
113
+ * @param {Object} options.manifest - The manifest (from readManifest).
114
+ * @param {Object} [options.ctx] - Optional bijou context override.
115
+ * @returns {string}
116
+ */
117
+ export function renderManifestView({ manifest, ctx = getCliContext() }) {
118
+ const m = manifest.toJSON ? manifest.toJSON() : manifest;
119
+ const sections = [renderBadges(m, ctx), renderMetadataSection(m, ctx)];
120
+
121
+ if (m.encryption) {
122
+ sections.push(renderEncryptionSection(m.encryption, ctx));
123
+ }
124
+ if (m.compression) {
125
+ sections.push(`${headerBox('Compression', { ctx })}\n${box(` algorithm ${m.compression.algorithm}`, { ctx })}`);
126
+ }
127
+ if (m.subManifests?.length) {
128
+ sections.push(renderSubManifestsSection(m, ctx));
129
+ }
130
+ if (m.chunks?.length) {
131
+ sections.push(renderChunksSection(m.chunks, ctx));
132
+ }
133
+
134
+ return `${sections.join('\n\n')}\n`;
135
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Animated progress bar for store/restore operations.
3
+ * Wires CasService EventEmitter events to a bijou progress bar on stderr.
4
+ */
5
+
6
+ import { statSync } from 'node:fs';
7
+ import { createAnimatedProgressBar } from '@flyingrobots/bijou';
8
+ import { getCliContext } from './context.js';
9
+
10
+ /**
11
+ * Format bytes as human-readable string.
12
+ */
13
+ function formatBytes(bytes) {
14
+ if (bytes < 1024) {
15
+ return `${bytes} B`;
16
+ }
17
+ if (bytes < 1024 * 1024) {
18
+ return `${(bytes / 1024).toFixed(1)} KiB`;
19
+ }
20
+ if (bytes < 1024 * 1024 * 1024) {
21
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
22
+ }
23
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
24
+ }
25
+
26
+ /**
27
+ * Create a progress tracker for store operations.
28
+ *
29
+ * @param {Object} options
30
+ * @param {string} options.filePath - Path to the file being stored.
31
+ * @param {number} options.chunkSize - Chunk size in bytes.
32
+ * @param {boolean} [options.quiet] - Suppress all progress output.
33
+ * @returns {{ attach(service: EventEmitter): void, detach(): void }}
34
+ */
35
+ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize }) {
36
+ if (quiet) {
37
+ return { attach() {}, detach() {} };
38
+ }
39
+
40
+ const ctx = getCliContext();
41
+ if (ctx.mode === 'pipe') {
42
+ return { attach() {}, detach() {} };
43
+ }
44
+
45
+ const fileSize = providedSize ?? statSync(filePath).size;
46
+ const totalChunks = fileSize === 0 ? 0 : Math.ceil(fileSize / chunkSize);
47
+
48
+ if (totalChunks === 0) {
49
+ return { attach() {}, detach() {} };
50
+ }
51
+
52
+ return createProgressTracker({ ctx, totalChunks, event: 'chunk:stored', label: 'Storing' });
53
+ }
54
+
55
+ /**
56
+ * Create a progress tracker for restore operations.
57
+ *
58
+ * @param {Object} options
59
+ * @param {number} options.totalChunks - Number of chunks to restore.
60
+ * @param {boolean} [options.quiet] - Suppress all progress output.
61
+ * @returns {{ attach(service: EventEmitter): void, detach(): void }}
62
+ */
63
+ export function createRestoreProgress({ totalChunks, quiet }) {
64
+ if (quiet || totalChunks === 0) {
65
+ return { attach() {}, detach() {} };
66
+ }
67
+
68
+ const ctx = getCliContext();
69
+ if (ctx.mode === 'pipe') {
70
+ return { attach() {}, detach() {} };
71
+ }
72
+
73
+ return createProgressTracker({ ctx, totalChunks, event: 'chunk:restored', label: 'Restoring' });
74
+ }
75
+
76
+ /**
77
+ * Internal: builds the progress tracker object.
78
+ */
79
+ function createProgressTracker({ ctx, totalChunks, event, label }) {
80
+ const width = Math.min(40, (ctx.runtime.columns || 80) - 30);
81
+ const bar = createAnimatedProgressBar({ width, showPercent: false, ctx });
82
+
83
+ let chunksProcessed = 0;
84
+ let bytesProcessed = 0;
85
+ let startTime = null;
86
+ let service = null;
87
+ let handler = null;
88
+
89
+ function onChunk({ size }) {
90
+ if (!startTime) {
91
+ startTime = Date.now();
92
+ }
93
+ chunksProcessed++;
94
+ bytesProcessed += size;
95
+
96
+ const pct = (chunksProcessed / totalChunks) * 100;
97
+ const elapsed = (Date.now() - startTime) / 1000;
98
+ const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
99
+
100
+ if (ctx.mode === 'interactive') {
101
+ const status = ` ${label} ${chunksProcessed}/${totalChunks} ${formatBytes(throughput)}/s `;
102
+ process.stderr.write(`\r\x1b[K${status}`);
103
+ bar.update(pct);
104
+ } else if (chunksProcessed === 1 || chunksProcessed === totalChunks || chunksProcessed % 10 === 0) {
105
+ ctx.io.write(`${label} ${chunksProcessed}/${totalChunks} ${Math.round(pct)}%\n`);
106
+ }
107
+ }
108
+
109
+ return {
110
+ attach(svc) {
111
+ service = svc;
112
+ handler = onChunk;
113
+ bar.start();
114
+ service.on(event, handler);
115
+ },
116
+ detach() {
117
+ if (service && handler) {
118
+ service.removeListener(event, handler);
119
+ }
120
+ const elapsed = startTime ? (Date.now() - startTime) / 1000 : 0;
121
+ const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
122
+ const msg = ` ${label} ${chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s`;
123
+ bar.stop(msg);
124
+ },
125
+ };
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -66,12 +66,21 @@
66
66
  "format": "prettier --write ."
67
67
  },
68
68
  "dependencies": {
69
+ "@flyingrobots/bijou": "^0.2.0",
70
+ "@flyingrobots/bijou-node": "^0.2.0",
71
+ "@flyingrobots/bijou-tui": "^0.2.0",
69
72
  "@git-stunts/alfred": "^0.10.0",
70
73
  "@git-stunts/plumbing": "^2.8.0",
71
74
  "cbor-x": "^1.6.0",
72
75
  "commander": "^14.0.3",
73
76
  "zod": "^3.24.1"
74
77
  },
78
+ "pnpm": {
79
+ "onlyBuiltDependencies": [
80
+ "cbor-extract",
81
+ "esbuild"
82
+ ]
83
+ },
75
84
  "devDependencies": {
76
85
  "@eslint/js": "^9.17.0",
77
86
  "eslint": "^9.17.0",