@git-stunts/git-cas 5.3.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +401 -4
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +872 -0
  6. package/README.md +219 -325
  7. package/SECURITY.md +993 -0
  8. package/SUPPORT.md +54 -0
  9. package/UPGRADING.md +299 -0
  10. package/bin/actions.js +72 -20
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +604 -450
  20. package/bin/io.js +86 -0
  21. package/bin/passphrase-source.js +266 -0
  22. package/bin/restore-output-target.js +28 -0
  23. package/bin/ui/blocks/asset-card.js +109 -0
  24. package/bin/ui/blocks/health-dashboard.js +149 -0
  25. package/bin/ui/blocks/heatmap-block.js +67 -0
  26. package/bin/ui/blocks/merkle-explorer.js +163 -0
  27. package/bin/ui/blocks/operation-feed.js +176 -0
  28. package/bin/ui/blocks/wizard-block.js +168 -0
  29. package/bin/ui/components/short-sha.js +36 -0
  30. package/bin/ui/context.js +56 -1
  31. package/bin/ui/dashboard-cmds.js +1578 -13
  32. package/bin/ui/dashboard-view.js +612 -145
  33. package/bin/ui/dashboard.js +998 -214
  34. package/bin/ui/encryption-card.js +69 -26
  35. package/bin/ui/heatmap.js +26 -54
  36. package/bin/ui/history-timeline.js +51 -19
  37. package/bin/ui/manifest-view.js +115 -60
  38. package/bin/ui/merkle-dag.js +83 -0
  39. package/bin/ui/progress.js +15 -9
  40. package/bin/ui/repo-treemap.js +328 -0
  41. package/bin/ui/shaders/bak-sneppen.js +180 -0
  42. package/bin/ui/shaders/fractal-zoom.js +99 -0
  43. package/bin/ui/shaders/merkle-tree.js +142 -0
  44. package/bin/ui/shaders/organic-flow.js +96 -0
  45. package/bin/ui/shaders/phase-portrait.js +93 -0
  46. package/bin/ui/store-wizard.js +296 -0
  47. package/bin/ui/theme.js +155 -0
  48. package/bin/ui/vault-report.js +495 -0
  49. package/build-info.json +4 -0
  50. package/docs/API.md +2224 -0
  51. package/docs/ENCRYPTION_MODES.md +33 -0
  52. package/docs/EXTENDING.md +174 -0
  53. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  54. package/docs/THREAT_MODEL.md +269 -0
  55. package/docs/VAULT_INTERNALS.md +251 -0
  56. package/docs/WALKTHROUGH.md +1868 -0
  57. package/docs/demo.gif +0 -0
  58. package/docs/releases/v6.0.0.md +104 -0
  59. package/examples/README.md +260 -0
  60. package/index.d.ts +208 -65
  61. package/index.js +163 -54
  62. package/package.json +35 -6
  63. package/scripts/migrate-encryption.js +680 -0
  64. package/src/domain/bytes/ByteLayout.js +96 -0
  65. package/src/domain/encoding/base64.js +91 -0
  66. package/src/domain/encoding/hex.js +14 -0
  67. package/src/domain/encoding/utf8.js +123 -0
  68. package/src/domain/encryption/schemes.js +132 -0
  69. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  70. package/src/domain/errors/CasError.d.ts +28 -0
  71. package/src/domain/errors/CasError.js +43 -6
  72. package/src/domain/errors/Codes.js +54 -0
  73. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  74. package/src/domain/errors/GitError.js +10 -0
  75. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  76. package/src/domain/errors/IntegrityError.js +10 -0
  77. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  78. package/src/domain/errors/InvalidOidError.js +10 -0
  79. package/src/domain/errors/InvalidOptionsError.js +10 -0
  80. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  81. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  82. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  83. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  84. package/src/domain/errors/PortNotImplementedError.js +10 -0
  85. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  86. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  87. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  88. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  89. package/src/domain/errors/createCasError.js +68 -0
  90. package/src/domain/errors/index.js +20 -0
  91. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  92. package/src/domain/helpers/codecBytes.js +34 -0
  93. package/src/domain/helpers/gitRefErrors.js +84 -0
  94. package/src/domain/helpers/scryptMaxmem.js +22 -0
  95. package/src/domain/outcomes/RestoreFailure.js +15 -0
  96. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  97. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  98. package/src/domain/outcomes/StoreFailure.js +15 -0
  99. package/src/domain/outcomes/StoreOutcome.js +11 -0
  100. package/src/domain/outcomes/StoreSuccess.js +17 -0
  101. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  102. package/src/domain/schemas/ManifestSchema.js +67 -13
  103. package/src/domain/services/CasService.d.ts +123 -38
  104. package/src/domain/services/CasService.js +298 -834
  105. package/src/domain/services/ChunkRepository.js +230 -0
  106. package/src/domain/services/CompressionStreams.js +72 -0
  107. package/src/domain/services/ConvergentEncryption.js +128 -0
  108. package/src/domain/services/GitTreeBuilder.js +86 -0
  109. package/src/domain/services/IntegrityVerifier.js +199 -0
  110. package/src/domain/services/KeyResolver.js +49 -42
  111. package/src/domain/services/ManifestDiff.js +56 -0
  112. package/src/domain/services/ManifestRepository.js +286 -0
  113. package/src/domain/services/PrefetchWindow.js +48 -0
  114. package/src/domain/services/RecipientService.js +157 -0
  115. package/src/domain/services/RedactingObservability.js +169 -0
  116. package/src/domain/services/RestorePipeline.js +68 -0
  117. package/src/domain/services/StorePipeline.js +201 -0
  118. package/src/domain/services/VaultKeyVerifier.js +101 -0
  119. package/src/domain/services/VaultMetadataCodec.js +206 -0
  120. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  121. package/src/domain/services/VaultPersistence.js +410 -0
  122. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  123. package/src/domain/services/VaultService.js +749 -251
  124. package/src/domain/services/VaultStateCache.js +225 -0
  125. package/src/domain/services/VaultTreeCodec.js +121 -0
  126. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  127. package/src/domain/strategies/Aad.js +39 -0
  128. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  129. package/src/domain/strategies/RestoreCompressed.js +40 -0
  130. package/src/domain/strategies/RestoreConvergent.js +44 -0
  131. package/src/domain/strategies/RestoreFramed.js +55 -0
  132. package/src/domain/strategies/RestorePlain.js +37 -0
  133. package/src/domain/strategies/RestoreStrategy.js +35 -0
  134. package/src/domain/strategies/RestoreWhole.js +135 -0
  135. package/src/domain/strategies/StoreConvergent.js +28 -0
  136. package/src/domain/strategies/StoreFramed.js +39 -0
  137. package/src/domain/strategies/StorePlain.js +20 -0
  138. package/src/domain/strategies/StoreStrategy.js +61 -0
  139. package/src/domain/strategies/StoreWhole.js +34 -0
  140. package/src/domain/value-objects/Chunk.js +1 -2
  141. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  142. package/src/domain/value-objects/Manifest.d.ts +40 -4
  143. package/src/domain/value-objects/Manifest.js +61 -20
  144. package/src/domain/value-objects/Oid.js +45 -0
  145. package/src/domain/value-objects/Slug.js +124 -0
  146. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  147. package/src/helpers/aesGcmMeta.js +55 -0
  148. package/src/helpers/canonicalBase64.js +1 -0
  149. package/src/helpers/kdfPolicy.js +194 -0
  150. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  151. package/src/infrastructure/adapters/FileIOHelper.js +178 -13
  152. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  153. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  154. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  155. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  156. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  157. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  158. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  159. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  160. package/src/infrastructure/chunkers/resolveChunker.js +3 -1
  161. package/src/infrastructure/codecs/CborCodec.js +3 -3
  162. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  163. package/src/infrastructure/createGitPlumbing.js +22 -0
  164. package/src/package-version.js +1 -0
  165. package/src/ports/ChunkingPort.js +3 -3
  166. package/src/ports/CodecPort.js +4 -4
  167. package/src/ports/CompressionPort.js +57 -0
  168. package/src/ports/CryptoPort.js +138 -50
  169. package/src/ports/GitPersistencePort.js +32 -2
  170. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  171. package/src/ports/GitRefPort.js +1 -1
  172. package/src/types/ambient.d.ts +10 -5
  173. package/test/CONVENTIONS.md +94 -0
  174. package/test/cycles/README.md +13 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * MerkleExplorer block — unified view of manifest chunk structure.
3
+ *
4
+ * Supports three modes:
5
+ * - 'table': flat chunk ledger (index, size, digest, blob)
6
+ * - 'tree': sub-manifest hierarchy as a tree
7
+ * - 'dag': full Merkle DAG visualization
8
+ *
9
+ * All three modes consume the same ManifestData input.
10
+ */
11
+
12
+ import { table, tree } from '@flyingrobots/bijou';
13
+ import { buildDagSource } from '../merkle-dag.js';
14
+ import { renderShortSha, shortenSha } from '../components/short-sha.js';
15
+
16
+ /**
17
+ * @typedef {import('../../../src/domain/value-objects/Manifest.js').ManifestData} ManifestData
18
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
19
+ * @typedef {'table' | 'tree' | 'dag'} MerkleViewMode
20
+ */
21
+
22
+ /**
23
+ * Format bytes as human-readable string.
24
+ *
25
+ * @param {number} bytes
26
+ * @returns {string}
27
+ */
28
+ function formatBytes(bytes) {
29
+ if (bytes < 1024) {
30
+ return `${bytes} B`;
31
+ }
32
+ if (bytes < 1024 * 1024) {
33
+ return `${(bytes / 1024).toFixed(1)} KiB`;
34
+ }
35
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
36
+ }
37
+
38
+ /**
39
+ * Determine which modes are available for a manifest.
40
+ *
41
+ * @param {ManifestData} manifest
42
+ * @returns {MerkleViewMode[]}
43
+ */
44
+ export function availableModes(manifest) {
45
+ /** @type {MerkleViewMode[]} */
46
+ const modes = ['table'];
47
+ if (manifest.subManifests?.length) {
48
+ modes.push('tree', 'dag');
49
+ }
50
+ return modes;
51
+ }
52
+
53
+ function clampIndex(index, length) {
54
+ return Math.max(0, Math.min(index, Math.max(0, length - 1)));
55
+ }
56
+
57
+ function chunkPage({ chunks, pageSize, selectedIndex }) {
58
+ const size = pageSize ? Math.max(1, pageSize) : Math.max(1, chunks.length);
59
+ const selected = clampIndex(selectedIndex ?? 0, chunks.length);
60
+ const pageStart = Math.floor(selected / size) * size;
61
+ return {
62
+ chunks: chunks.slice(pageStart, pageStart + size),
63
+ selected,
64
+ pageStart,
65
+ pageEnd: Math.min(chunks.length, pageStart + size),
66
+ page: Math.floor(pageStart / size) + 1,
67
+ pages: Math.max(1, Math.ceil(chunks.length / size)),
68
+ };
69
+ }
70
+
71
+ function shaCharsForWidth(width) {
72
+ if (!Number.isFinite(width)) { return 16; }
73
+ if (width >= 92) { return 20; }
74
+ if (width >= 72) { return 16; }
75
+ return 12;
76
+ }
77
+
78
+ /**
79
+ * Render the chunk table view.
80
+ *
81
+ * @param {ManifestData} manifest
82
+ * @param {BijouContext} ctx
83
+ * @param {{ pageSize?: number, selectedIndex?: number, width?: number }} [options]
84
+ * @returns {string}
85
+ */
86
+ export function renderChunkTable(manifest, ctx, options = {}) {
87
+ const chunks = manifest.chunks || [];
88
+ const page = chunkPage({ chunks, pageSize: options.pageSize, selectedIndex: options.selectedIndex });
89
+ const shaChars = shaCharsForWidth(options.width);
90
+ const rows = page.chunks.map((c, offset) => {
91
+ const absoluteIndex = page.pageStart + offset;
92
+ const selected = options.selectedIndex !== undefined && absoluteIndex === page.selected;
93
+ return [
94
+ selected ? '>' : ' ',
95
+ String(c.index ?? absoluteIndex),
96
+ formatBytes(c.size),
97
+ renderShortSha(c.digest, ctx, { chars: shaChars, selected }),
98
+ renderShortSha(c.blob, ctx, { chars: shaChars, selected }),
99
+ ];
100
+ });
101
+ const chunkTable = table({
102
+ columns: [
103
+ { header: '', width: 1 },
104
+ { header: '#', width: 5 },
105
+ { header: 'Size', width: 10 },
106
+ { header: 'Digest', width: shaChars + 3 },
107
+ { header: 'Blob', width: shaChars + 3 },
108
+ ],
109
+ rows,
110
+ ctx,
111
+ });
112
+ const suffix = options.pageSize && chunks.length > options.pageSize
113
+ ? `\n Showing ${page.pageStart + 1}-${page.pageEnd} of ${chunks.length} Page ${page.page}/${page.pages}`
114
+ : '';
115
+ return `${chunkTable}${suffix}`;
116
+ }
117
+
118
+ /**
119
+ * Render the sub-manifest tree view.
120
+ *
121
+ * @param {ManifestData} manifest
122
+ * @param {BijouContext} ctx
123
+ * @returns {string}
124
+ */
125
+ export function renderSubManifestTree(manifest, ctx) {
126
+ const subs = manifest.subManifests || [];
127
+ if (subs.length === 0) {
128
+ return 'No sub-manifests';
129
+ }
130
+ const nodes = subs.map((sm, i) => ({
131
+ label: `sub-${i} ${sm.chunkCount} chunks start: ${sm.startIndex} oid: ${shortenSha(sm.oid, 8)}`,
132
+ }));
133
+ return tree(nodes, { ctx });
134
+ }
135
+
136
+ /**
137
+ * Build DAG source data for the dagPane component.
138
+ * Re-exports from merkle-dag.js for convenience.
139
+ *
140
+ * @param {ManifestData} manifest
141
+ * @returns {ReturnType<typeof buildDagSource>}
142
+ */
143
+ export function buildMerkleDagSource(manifest) {
144
+ return buildDagSource(manifest);
145
+ }
146
+
147
+ /**
148
+ * Render a merkle explorer view in the specified mode.
149
+ *
150
+ * @param {ManifestData} manifest
151
+ * @param {MerkleViewMode} mode
152
+ * @param {BijouContext} ctx
153
+ * @returns {string}
154
+ */
155
+ export function renderMerkleExplorer(manifest, mode, ctx) {
156
+ if (mode === 'tree') {
157
+ return renderSubManifestTree(manifest, ctx);
158
+ }
159
+ if (mode === 'dag') {
160
+ return `[DAG mode — use 'm' key in dashboard for interactive view]`;
161
+ }
162
+ return renderChunkTable(manifest, ctx);
163
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * OperationFeed block — persistent operation history with progress tracking.
3
+ *
4
+ * Tracks store/restore operations with status, duration, and progress.
5
+ * Complements the transient toast notification system with a persistent
6
+ * log accessible via a keybinding.
7
+ */
8
+
9
+ import { badge, surfaceToString } from '@flyingrobots/bijou';
10
+ import { hstackSurface } from '@flyingrobots/bijou-tui';
11
+ import { themeText } from '../theme.js';
12
+
13
+ /**
14
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
15
+ */
16
+
17
+ /**
18
+ * @typedef {'pending' | 'running' | 'done' | 'error'} OpStatus
19
+ */
20
+
21
+ /**
22
+ * @typedef {Object} OperationEntry
23
+ * @property {string} id
24
+ * @property {'store' | 'restore'} type
25
+ * @property {string} slug
26
+ * @property {OpStatus} status
27
+ * @property {number} startTime
28
+ * @property {number | null} endTime
29
+ * @property {number} chunksTotal
30
+ * @property {number} chunksProcessed
31
+ * @property {string | null} error
32
+ */
33
+
34
+ /**
35
+ * @typedef {Object} OperationFeedState
36
+ * @property {OperationEntry[]} entries
37
+ * @property {number} maxEntries
38
+ */
39
+
40
+ /**
41
+ * Create an empty feed state.
42
+ *
43
+ * @param {{ maxEntries?: number }} [opts]
44
+ * @returns {OperationFeedState}
45
+ */
46
+ export function createFeedState(opts = {}) {
47
+ return { entries: [], maxEntries: opts.maxEntries ?? 50 };
48
+ }
49
+
50
+ /**
51
+ * Start tracking a new operation.
52
+ *
53
+ * @param {OperationFeedState} state
54
+ * @param {{ type: 'store' | 'restore', slug: string, chunksTotal?: number }} op
55
+ * @returns {OperationFeedState}
56
+ */
57
+ export function feedStartOp(state, op) {
58
+ const entry = {
59
+ id: `${op.type}-${op.slug}-${Date.now()}`,
60
+ type: op.type,
61
+ slug: op.slug,
62
+ status: /** @type {OpStatus} */ ('running'),
63
+ startTime: Date.now(),
64
+ endTime: null,
65
+ chunksTotal: op.chunksTotal ?? 0,
66
+ chunksProcessed: 0,
67
+ error: null,
68
+ };
69
+ const entries = [entry, ...state.entries].slice(0, state.maxEntries);
70
+ return { ...state, entries };
71
+ }
72
+
73
+ /**
74
+ * Update progress for a running operation.
75
+ *
76
+ * @param {OperationFeedState} state
77
+ * @param {string} id
78
+ * @param {number} chunksProcessed
79
+ * @returns {OperationFeedState}
80
+ */
81
+ export function feedUpdateProgress(state, id, chunksProcessed) {
82
+ const entries = state.entries.map((e) =>
83
+ e.id === id ? { ...e, chunksProcessed } : e,
84
+ );
85
+ return { ...state, entries };
86
+ }
87
+
88
+ /**
89
+ * Mark an operation as completed.
90
+ *
91
+ * @param {OperationFeedState} state
92
+ * @param {string} id
93
+ * @returns {OperationFeedState}
94
+ */
95
+ export function feedCompleteOp(state, id) {
96
+ const entries = state.entries.map((e) =>
97
+ e.id === id ? { ...e, status: /** @type {OpStatus} */ ('done'), endTime: Date.now() } : e,
98
+ );
99
+ return { ...state, entries };
100
+ }
101
+
102
+ /**
103
+ * Mark an operation as failed.
104
+ *
105
+ * @param {OperationFeedState} state
106
+ * @param {string} id
107
+ * @param {string} error
108
+ * @returns {OperationFeedState}
109
+ */
110
+ export function feedFailOp(state, id, error) {
111
+ const entries = state.entries.map((e) =>
112
+ e.id === id ? { ...e, status: /** @type {OpStatus} */ ('error'), endTime: Date.now(), error } : e,
113
+ );
114
+ return { ...state, entries };
115
+ }
116
+
117
+ /**
118
+ * Format a duration in ms to human-readable.
119
+ *
120
+ * @param {number} ms
121
+ * @returns {string}
122
+ */
123
+ function formatDuration(ms) {
124
+ if (ms < 1000) {
125
+ return `${ms}ms`;
126
+ }
127
+ return `${(ms / 1000).toFixed(1)}s`;
128
+ }
129
+
130
+ /** @type {Record<OpStatus, 'info' | 'success' | 'danger' | 'warning'>} */
131
+ const STATUS_VARIANTS = {
132
+ pending: 'info',
133
+ running: 'warning',
134
+ done: 'success',
135
+ error: 'danger',
136
+ };
137
+
138
+ /**
139
+ * Render a single operation entry.
140
+ *
141
+ * @param {OperationEntry} entry
142
+ * @param {BijouContext} ctx
143
+ * @returns {string}
144
+ */
145
+ function renderFeedEntry(entry, ctx) {
146
+ const statusBadge = badge(entry.status, { variant: STATUS_VARIANTS[entry.status], ctx });
147
+ const typeBadge = badge(entry.type, { variant: 'neutral', ctx });
148
+ const header = surfaceToString(hstackSurface(1, statusBadge, typeBadge), ctx.style);
149
+ const slug = themeText(ctx, entry.slug, { tone: 'primary' });
150
+ const duration = entry.endTime
151
+ ? formatDuration(entry.endTime - entry.startTime)
152
+ : formatDuration(Date.now() - entry.startTime);
153
+ const progress = entry.chunksTotal > 0
154
+ ? ` ${entry.chunksProcessed}/${entry.chunksTotal} chunks`
155
+ : '';
156
+ const error = entry.error
157
+ ? `\n ${themeText(ctx, entry.error, { tone: 'danger' })}`
158
+ : '';
159
+ return `${header} ${slug} ${duration}${progress}${error}`;
160
+ }
161
+
162
+ /**
163
+ * Render the full operation feed.
164
+ *
165
+ * @param {OperationFeedState} state
166
+ * @param {BijouContext} ctx
167
+ * @returns {string}
168
+ */
169
+ export function renderOperationFeed(state, ctx) {
170
+ if (state.entries.length === 0) {
171
+ return themeText(ctx, 'No operations recorded.', { tone: 'subdued' });
172
+ }
173
+ const title = themeText(ctx, `Operations (${state.entries.length})`, { tone: 'brand', bold: true });
174
+ const entries = state.entries.map((e) => renderFeedEntry(e, ctx));
175
+ return [title, '', ...entries].join('\n');
176
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * WizardBlock — reusable step-based wizard infrastructure.
3
+ *
4
+ * Provides generic step types (text input, select list, toggle, confirm),
5
+ * step navigation, and rendering helpers. Application wizards define
6
+ * their steps declaratively and delegate key handling + rendering here.
7
+ */
8
+
9
+ import { boxSurface, parseAnsiToSurface } from '@flyingrobots/bijou';
10
+ import { themeText } from '../theme.js';
11
+
12
+ /**
13
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
14
+ * @typedef {import('@flyingrobots/bijou').Surface} Surface
15
+ */
16
+
17
+ /**
18
+ * @typedef {Object} WizardStepDef
19
+ * @property {string} id - Step identifier.
20
+ * @property {string} label - Human-readable step label.
21
+ * @property {'text' | 'select' | 'toggle' | 'confirm'} type - Step input type.
22
+ * @property {string} [prompt] - Prompt text shown above the input.
23
+ * @property {string} [hint] - Help text shown below the input.
24
+ * @property {string[]} [options] - Options for 'select' type.
25
+ */
26
+
27
+ const WIZARD_MIN_WIDTH = 36;
28
+ const WIZARD_MAX_WIDTH = 60;
29
+ const WIZARD_MARGIN = 4;
30
+ const WIZARD_MIN_HEIGHT = 8;
31
+ const WIZARD_PADDING = 4;
32
+
33
+ /**
34
+ * Render a select list with focus indicator.
35
+ *
36
+ * @param {number} focusIndex
37
+ * @param {string[]} options
38
+ * @param {BijouContext} ctx
39
+ * @returns {string}
40
+ */
41
+ export function renderSelectList(focusIndex, options, ctx) {
42
+ return options.map((opt, i) => {
43
+ const indicator = i === focusIndex ? '\u25b8' : ' ';
44
+ const tone = i === focusIndex ? 'primary' : 'secondary';
45
+ return `${indicator} ${themeText(ctx, opt, { tone })}`;
46
+ }).join('\n');
47
+ }
48
+
49
+ /**
50
+ * Render a text input field with cursor.
51
+ *
52
+ * @param {string} value
53
+ * @returns {string}
54
+ */
55
+ export function renderTextInput(value) {
56
+ return `${value}\u2588`;
57
+ }
58
+
59
+ /**
60
+ * Render a toggle field.
61
+ *
62
+ * @param {boolean} value
63
+ * @param {BijouContext} ctx
64
+ * @returns {string}
65
+ */
66
+ export function renderToggle(value, ctx) {
67
+ const toggle = value ? '[x] enabled' : '[ ] disabled';
68
+ return themeText(ctx, toggle, { tone: 'primary' });
69
+ }
70
+
71
+ /**
72
+ * Render a labeled key-value line.
73
+ *
74
+ * @param {BijouContext} ctx
75
+ * @param {string} label
76
+ * @param {string} value
77
+ * @returns {string}
78
+ */
79
+ export function renderFieldLine(ctx, label, value) {
80
+ return `${themeText(ctx, label, { tone: 'accent' })} ${themeText(ctx, value || '-', { tone: 'primary' })}`;
81
+ }
82
+
83
+ /**
84
+ * Render a wizard panel surface with title and step indicator.
85
+ *
86
+ * Uses parseAnsiToSurface for height measurement instead of
87
+ * string line counting.
88
+ *
89
+ * @param {Object} opts
90
+ * @param {string} opts.title - Panel title with step indicator.
91
+ * @param {string} opts.body - Rendered body content.
92
+ * @param {number} opts.screenWidth - Available screen width.
93
+ * @param {number} opts.screenHeight - Available screen height.
94
+ * @param {BijouContext} opts.ctx
95
+ * @returns {Surface}
96
+ */
97
+ export function renderWizardPanel(opts) {
98
+ const panelWidth = Math.max(WIZARD_MIN_WIDTH, Math.min(WIZARD_MAX_WIDTH, opts.screenWidth - WIZARD_MARGIN));
99
+ const innerWidth = Math.max(1, panelWidth - 2);
100
+ const bodySurface = parseAnsiToSurface(opts.body, innerWidth, 999);
101
+ const panelHeight = Math.max(WIZARD_MIN_HEIGHT, Math.min(bodySurface.height + WIZARD_PADDING, opts.screenHeight));
102
+ const innerHeight = Math.max(1, panelHeight - 2);
103
+ const content = parseAnsiToSurface(opts.body, innerWidth, innerHeight);
104
+ return boxSurface(content, {
105
+ ctx: opts.ctx,
106
+ title: opts.title,
107
+ width: panelWidth,
108
+ height: panelHeight,
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Handle key events for a select-list step.
114
+ *
115
+ * @param {number} selectIndex - Current focus index.
116
+ * @param {number} optionCount - Total options.
117
+ * @param {string} key - Key pressed.
118
+ * @returns {{ selectIndex: number, confirmed: boolean }}
119
+ */
120
+ export function handleSelectKey(selectIndex, optionCount, key) {
121
+ if (key === 'enter') {
122
+ return { selectIndex, confirmed: true };
123
+ }
124
+ if (key === 'j' || key === 'down') {
125
+ return { selectIndex: Math.min(selectIndex + 1, optionCount - 1), confirmed: false };
126
+ }
127
+ if (key === 'k' || key === 'up') {
128
+ return { selectIndex: Math.max(selectIndex - 1, 0), confirmed: false };
129
+ }
130
+ return { selectIndex, confirmed: false };
131
+ }
132
+
133
+ /**
134
+ * Handle key events for a text-input step.
135
+ *
136
+ * @param {string} value - Current input value.
137
+ * @param {string} key - Key pressed.
138
+ * @returns {{ value: string, confirmed: boolean }}
139
+ */
140
+ export function handleTextKey(value, key) {
141
+ if (key === 'enter' && value.length > 0) {
142
+ return { value, confirmed: true };
143
+ }
144
+ if (key === 'backspace') {
145
+ return { value: value.slice(0, -1), confirmed: false };
146
+ }
147
+ if (key.length === 1) {
148
+ return { value: value + key, confirmed: false };
149
+ }
150
+ return { value, confirmed: false };
151
+ }
152
+
153
+ /**
154
+ * Handle key events for a toggle step.
155
+ *
156
+ * @param {boolean} value - Current toggle value.
157
+ * @param {string} key - Key pressed.
158
+ * @returns {{ value: boolean, confirmed: boolean }}
159
+ */
160
+ export function handleToggleKey(value, key) {
161
+ if (key === 'enter') {
162
+ return { value, confirmed: true };
163
+ }
164
+ if (key === 'space' || key === 'j' || key === 'k') {
165
+ return { value: !value, confirmed: false };
166
+ }
167
+ return { value, confirmed: false };
168
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Compact SHA/OID presentation with a footer-friendly full-value affordance.
3
+ */
4
+
5
+ import { themeText } from '../theme.js';
6
+
7
+ /**
8
+ * @param {string | null | undefined} value
9
+ * @param {number} [chars]
10
+ * @returns {string}
11
+ */
12
+ export function shortenSha(value, chars = 12) {
13
+ if (typeof value !== 'string' || value.length === 0) { return '-'; }
14
+ const safeChars = Math.max(4, Math.floor(chars));
15
+ return value.length > safeChars ? `${value.slice(0, safeChars)}...` : value;
16
+ }
17
+
18
+ /**
19
+ * @param {string | null | undefined} value
20
+ * @param {import('@flyingrobots/bijou').BijouContext} ctx
21
+ * @param {{ chars?: number, selected?: boolean, tone?: string }} [options]
22
+ * @returns {string}
23
+ */
24
+ export function renderShortSha(value, ctx, options = {}) {
25
+ const tone = options.selected ? 'accent' : (options.tone ?? 'secondary');
26
+ return themeText(ctx, shortenSha(value, options.chars), { tone, bold: options.selected ?? false });
27
+ }
28
+
29
+ /**
30
+ * @param {string} label
31
+ * @param {string | null | undefined} value
32
+ * @returns {string}
33
+ */
34
+ export function shortShaStatus(label, value) {
35
+ return typeof value === 'string' && value.length > 0 ? `${label} ${value}` : '';
36
+ }
package/bin/ui/context.js CHANGED
@@ -3,7 +3,8 @@
3
3
  */
4
4
 
5
5
  import { createBijou } from '@flyingrobots/bijou';
6
- import { nodeRuntime, chalkStyle } from '@flyingrobots/bijou-node';
6
+ import { nodeRuntime, nodeIO, chalkStyle } from '@flyingrobots/bijou-node';
7
+ import { GIT_CAS_THEME } from './theme.js';
7
8
 
8
9
  /** @type {import('@flyingrobots/bijou').BijouContext | null} */
9
10
  let ctx = null;
@@ -24,10 +25,64 @@ export function getCliContext() {
24
25
  runtime,
25
26
  io: stderrIO(),
26
27
  style: chalkStyle(noColor),
28
+ theme: GIT_CAS_THEME,
27
29
  });
28
30
  return ctx;
29
31
  }
30
32
 
33
+ /**
34
+ * Detect the display mode for full-screen CLI TUI flows.
35
+ *
36
+ * Unlike Bijou's default detection, NO_COLOR only disables styling here.
37
+ * It must not downgrade a real TTY session out of interactive mode.
38
+ *
39
+ * @param {import('@flyingrobots/bijou').RuntimePort} runtime
40
+ * @returns {'interactive' | 'pipe' | 'static' | 'accessible'}
41
+ */
42
+ export function detectCliTuiMode(runtime) {
43
+ if (runtime.env('BIJOU_ACCESSIBLE') === '1') {
44
+ return 'accessible';
45
+ }
46
+ if (runtime.env('TERM') === 'dumb') {
47
+ return 'pipe';
48
+ }
49
+ if (!runtime.stdoutIsTTY || !runtime.stdinIsTTY) {
50
+ return 'pipe';
51
+ }
52
+ if (runtime.env('CI') !== undefined) {
53
+ return 'static';
54
+ }
55
+ return 'interactive';
56
+ }
57
+
58
+ /**
59
+ * Returns a bijou context for interactive CLI TUI flows.
60
+ *
61
+ * This keeps NO_COLOR behavior for styling while preserving interactive mode
62
+ * on real TTYs.
63
+ *
64
+ * @param {{
65
+ * runtime?: import('@flyingrobots/bijou').RuntimePort,
66
+ * io?: import('@flyingrobots/bijou').IOPort,
67
+ * style?: import('@flyingrobots/bijou').StylePort,
68
+ * }} [options]
69
+ * @returns {import('@flyingrobots/bijou').BijouContext}
70
+ */
71
+ export function createCliTuiContext(options = {}) {
72
+ const runtime = options.runtime || nodeRuntime();
73
+ const noColor = runtime.env('NO_COLOR') !== undefined;
74
+ const base = createBijou({
75
+ runtime,
76
+ io: options.io || nodeIO(),
77
+ style: options.style || chalkStyle(noColor),
78
+ theme: GIT_CAS_THEME,
79
+ });
80
+ return {
81
+ ...base,
82
+ mode: detectCliTuiMode(runtime),
83
+ };
84
+ }
85
+
31
86
  /**
32
87
  * @returns {import('@flyingrobots/bijou').IOPort}
33
88
  */