@git-stunts/git-cas 5.3.2 → 6.0.1

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 +1027 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +449 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +926 -0
  6. package/README.md +106 -366
  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 +1255 -212
  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 +367 -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 +2254 -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 +273 -80
  60. package/index.js +220 -59
  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 +153 -53
  103. package/src/domain/services/CasService.js +322 -837
  104. package/src/domain/services/ChunkRepository.js +268 -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 +180 -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 +10 -6
  160. package/src/infrastructure/codecs/CborCodec.js +3 -3
  161. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  162. package/src/infrastructure/createGitPlumbing.js +22 -0
  163. package/src/package-version.js +1 -0
  164. package/src/ports/ChunkingPort.js +3 -3
  165. package/src/ports/CodecPort.js +4 -4
  166. package/src/ports/CompressionPort.js +57 -0
  167. package/src/ports/CryptoPort.js +138 -50
  168. package/src/ports/GitPersistencePort.js +32 -2
  169. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  170. package/src/ports/GitRefPort.js +1 -1
  171. package/src/types/ambient.d.ts +10 -5
  172. package/test/CONVENTIONS.md +94 -0
  173. package/test/cycles/README.md +13 -0
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Merkle DAG data builder — converts a manifest into dagPane source nodes.
3
+ */
4
+
5
+ /**
6
+ * @typedef {import('../../src/domain/value-objects/Manifest.js').ManifestData} ManifestData
7
+ */
8
+
9
+ /**
10
+ * Format bytes as human-readable string.
11
+ *
12
+ * @param {number} bytes
13
+ * @returns {string}
14
+ */
15
+ function formatBytes(bytes) {
16
+ if (bytes < 1024) {
17
+ return `${bytes} B`;
18
+ }
19
+ if (bytes < 1024 * 1024) {
20
+ return `${(bytes / 1024).toFixed(1)} KiB`;
21
+ }
22
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
23
+ }
24
+
25
+ /**
26
+ * Build dagPane source nodes from a manifest.
27
+ *
28
+ * For a manifest with sub-manifests (Merkle tree):
29
+ * root → sub-0, sub-1, ... → chunk nodes per sub-manifest
30
+ *
31
+ * For a flat manifest (no sub-manifests):
32
+ * root → chunk-0, chunk-1, ...
33
+ *
34
+ * @param {ManifestData} manifest
35
+ * @returns {{ id: string, label: string, children: string[] }[]}
36
+ */
37
+ export function buildDagSource(manifest) {
38
+ const nodes = [];
39
+ const subs = manifest.subManifests || [];
40
+ const chunks = manifest.chunks || [];
41
+
42
+ if (subs.length > 0) {
43
+ const rootChildren = subs.map((_, i) => `sub-${i}`);
44
+ nodes.push({
45
+ id: 'root',
46
+ label: `${manifest.slug} ${formatBytes(manifest.size)} ${chunks.length} chunks`,
47
+ children: rootChildren,
48
+ });
49
+ for (let i = 0; i < subs.length; i++) {
50
+ const sub = subs[i];
51
+ const subChunks = chunks.slice(sub.startIndex, sub.startIndex + sub.chunkCount);
52
+ const chunkChildren = subChunks.map((c) => `chunk-${c.index}`);
53
+ nodes.push({
54
+ id: `sub-${i}`,
55
+ label: `sub-${i} ${sub.chunkCount} chunks ${sub.oid.slice(0, 8)}...`,
56
+ children: chunkChildren,
57
+ });
58
+ for (const c of subChunks) {
59
+ nodes.push({
60
+ id: `chunk-${c.index}`,
61
+ label: `#${c.index} ${formatBytes(c.size)} ${c.digest.slice(0, 8)}`,
62
+ children: [],
63
+ });
64
+ }
65
+ }
66
+ } else {
67
+ const chunkChildren = chunks.map((c) => `chunk-${c.index}`);
68
+ nodes.push({
69
+ id: 'root',
70
+ label: `${manifest.slug} ${formatBytes(manifest.size)}`,
71
+ children: chunkChildren,
72
+ });
73
+ for (const c of chunks) {
74
+ nodes.push({
75
+ id: `chunk-${c.index}`,
76
+ label: `#${c.index} ${formatBytes(c.size)} ${c.digest.slice(0, 8)}`,
77
+ children: [],
78
+ });
79
+ }
80
+ }
81
+
82
+ return nodes;
83
+ }
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { statSync } from 'node:fs';
7
- import { createAnimatedProgressBar } from '@flyingrobots/bijou';
7
+ import { CLEAR_LINE_RETURN, progressBar } from '@flyingrobots/bijou';
8
8
  import { getCliContext } from './context.js';
9
9
 
10
10
  /**
@@ -99,7 +99,7 @@ export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx })
99
99
  *
100
100
  * @param {{ size: number }} evt
101
101
  * @param {TrackerState} state
102
- * @param {{ ctx: import('@flyingrobots/bijou').BijouContext, totalChunks: number, label: string, bar: { update(pct: number): void } }} deps
102
+ * @param {{ ctx: import('@flyingrobots/bijou').BijouContext, totalChunks: number, label: string, width: number }} deps
103
103
  */
104
104
  function handleChunkEvent({ size }, state, deps) {
105
105
  if (!state.startTime) { state.startTime = Date.now(); }
@@ -110,10 +110,10 @@ function handleChunkEvent({ size }, state, deps) {
110
110
  const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
111
111
  if (deps.ctx.mode === 'interactive') {
112
112
  const status = ` ${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${formatBytes(throughput)}/s `;
113
- deps.ctx.io.write(`\r\x1b[K${status}`);
114
- deps.bar.update(pct);
113
+ const barStr = progressBar(pct, { width: deps.width, showPercent: false, ctx: deps.ctx });
114
+ deps.ctx.io.writeError(`${CLEAR_LINE_RETURN}${status}${barStr}`);
115
115
  } else if (state.chunksProcessed === 1 || state.chunksProcessed === deps.totalChunks || state.chunksProcessed % 10 === 0) {
116
- deps.ctx.io.write(`${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${Math.round(pct)}%\n`);
116
+ deps.ctx.io.writeError(`${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${Math.round(pct)}%\n`);
117
117
  }
118
118
  }
119
119
 
@@ -125,24 +125,30 @@ function handleChunkEvent({ size }, state, deps) {
125
125
  */
126
126
  function createProgressTracker({ ctx, totalChunks, event, label }) {
127
127
  const width = Math.min(40, (ctx.runtime.columns || 80) - 30);
128
- const bar = createAnimatedProgressBar({ width, showPercent: false, ctx });
129
128
  /** @type {TrackerState} */
130
129
  const state = { chunksProcessed: 0, bytesProcessed: 0, startTime: null, service: null, handler: null };
131
- const deps = { ctx, totalChunks, label, bar };
130
+ const deps = { ctx, totalChunks, label, width };
132
131
 
133
132
  return {
134
133
  /** @param {Observer} svc */
135
134
  attach(svc) {
136
135
  state.service = svc;
137
136
  state.handler = (/** @type {{ size: number }} */ evt) => handleChunkEvent(evt, state, deps);
138
- bar.start();
137
+ if (ctx.mode === 'interactive') {
138
+ ctx.io.writeError('\x1b[?25l'); // hide cursor
139
+ handleChunkEvent({ size: 0 }, state, deps);
140
+ }
139
141
  state.service.on(event, state.handler);
140
142
  },
141
143
  detach() {
142
144
  if (state.service && state.handler) { state.service.removeListener(event, state.handler); }
143
145
  const elapsed = state.startTime ? (Date.now() - state.startTime) / 1000 : 0;
144
146
  const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
145
- bar.stop(` ${label} ${state.chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s`);
147
+ if (ctx.mode === 'interactive') {
148
+ ctx.io.writeError(`${CLEAR_LINE_RETURN} ${label} ${state.chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s\n\x1b[?25h`); // show cursor
149
+ } else {
150
+ ctx.io.writeError(`${label} ${state.chunksProcessed}/${totalChunks} done\n`);
151
+ }
146
152
  },
147
153
  };
148
154
  }
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Render a semantic repository treemap for the dashboard.
3
+ */
4
+
5
+ /**
6
+ * @typedef {import('./dashboard-cmds.js').RepoTreemapReport} RepoTreemapReport
7
+ * @typedef {import('./dashboard-cmds.js').RepoTreemapTile} RepoTreemapTile
8
+ * @typedef {import('./dashboard.js').DashSource} DashSource
9
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
10
+ */
11
+
12
+ import { GIT_CAS_PALETTE } from './theme.js';
13
+
14
+ const TILE_COLOR = {
15
+ worktree: GIT_CAS_PALETTE.cyan,
16
+ git: GIT_CAS_PALETTE.orange,
17
+ ref: GIT_CAS_PALETTE.sky,
18
+ vault: GIT_CAS_PALETTE.ghost,
19
+ cas: GIT_CAS_PALETTE.ruby,
20
+ meta: GIT_CAS_PALETTE.slate,
21
+ };
22
+
23
+ const TILE_FILL = {
24
+ worktree: '█',
25
+ git: '▓',
26
+ ref: '▒',
27
+ vault: '■',
28
+ cas: '▦',
29
+ meta: '░',
30
+ };
31
+
32
+ const TILE_LABEL = {
33
+ worktree: 'worktree',
34
+ git: 'git',
35
+ ref: 'refs',
36
+ vault: 'vault',
37
+ cas: 'source',
38
+ meta: 'other',
39
+ };
40
+
41
+ function formatBytes(bytes) {
42
+ if (bytes < 1024) { return `${bytes}B`; }
43
+ if (bytes < 1024 * 1024) { return `${(bytes / 1024).toFixed(1)}K`; }
44
+ if (bytes < 1024 * 1024 * 1024) { return `${(bytes / (1024 * 1024)).toFixed(1)}M`; }
45
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}G`;
46
+ }
47
+
48
+ function sourceLabel(source) {
49
+ if (source.type === 'vault') { return 'vault'; }
50
+ if (source.type === 'ref') { return `ref ${source.ref}`; }
51
+ return `oid ${source.treeOid}`;
52
+ }
53
+
54
+ function clip(text, width) {
55
+ if (width <= 0) { return ''; }
56
+ if (text.length <= width) { return text; }
57
+ return width <= 1 ? text.slice(0, width) : `${text.slice(0, width - 1)}…`;
58
+ }
59
+
60
+ function currentLevelLabel(report) {
61
+ return report.breadcrumb.join(' > ');
62
+ }
63
+
64
+ function tailClip(text, width) {
65
+ if (width <= 0) { return ''; }
66
+ if (text.length <= width) { return text; }
67
+ return width <= 3 ? clip(text, width) : `...${text.slice(text.length - (width - 3))}`;
68
+ }
69
+
70
+ function findWrapIndex(line, width) {
71
+ const splitAt = Math.min(width, line.length);
72
+ const boundaryChar = line[splitAt];
73
+ if (boundaryChar && /\s/u.test(boundaryChar)) { return splitAt; }
74
+ let backtrack = splitAt;
75
+ while (backtrack > 0 && !/\s/u.test(line[backtrack - 1])) { backtrack--; }
76
+ return backtrack > 0 ? backtrack : splitAt;
77
+ }
78
+
79
+ function wrapLine(line, width) {
80
+ if (line.length === 0) { return ['']; }
81
+ const wrapped = [];
82
+ let remaining = line;
83
+ while (remaining.length > width) {
84
+ const splitAt = Math.min(width, remaining.length);
85
+ const wrapIndex = findWrapIndex(remaining, width);
86
+ const chunk = remaining.slice(0, wrapIndex).replace(/\s+$/u, '');
87
+ wrapped.push(chunk || remaining.slice(0, splitAt));
88
+ let nextStart = wrapIndex;
89
+ while (nextStart < remaining.length && /\s/u.test(remaining[nextStart])) { nextStart++; }
90
+ remaining = remaining.slice(nextStart);
91
+ }
92
+ if (remaining.length > 0 || wrapped.length === 0) { wrapped.push(remaining); }
93
+ return wrapped;
94
+ }
95
+
96
+ function wrapText(text, width) {
97
+ if (width <= 0) { return ['']; }
98
+ return text.split('\n').flatMap((line) => wrapLine(line, width));
99
+ }
100
+
101
+ function limitLines(lines, width, maxLines) {
102
+ if (lines.length <= maxLines) { return lines; }
103
+ const capped = lines.slice(0, maxLines);
104
+ capped[maxLines - 1] = `${clip(capped[maxLines - 1], Math.max(1, width - 1))}…`;
105
+ return capped;
106
+ }
107
+
108
+ function formatPercent(value, total) {
109
+ return total <= 0 ? '0.0%' : `${((value / total) * 100).toFixed(1)}%`;
110
+ }
111
+
112
+ function sortTilesByValue(tiles) {
113
+ return [...tiles].sort((left, right) => right.value - left.value || left.label.localeCompare(right.label));
114
+ }
115
+
116
+ function splitTiles(tiles) {
117
+ if (tiles.length <= 1) { return [tiles, []]; }
118
+ const total = tiles.reduce((sum, tile) => sum + tile.value, 0);
119
+ const target = total / 2;
120
+ let bestIndex = 1;
121
+ let bestDelta = Infinity;
122
+ let running = 0;
123
+ for (let index = 1; index < tiles.length; index++) {
124
+ running += tiles[index - 1].value;
125
+ const delta = Math.abs(target - running);
126
+ if (delta < bestDelta) {
127
+ bestDelta = delta;
128
+ bestIndex = index;
129
+ }
130
+ }
131
+ return [tiles.slice(0, bestIndex), tiles.slice(bestIndex)];
132
+ }
133
+
134
+ function layoutTreemap(tiles, rect, vertical = rect.width >= rect.height) {
135
+ if (tiles.length === 0 || rect.width <= 0 || rect.height <= 0) { return []; }
136
+ if (tiles.length === 1) { return [{ tile: tiles[0], ...rect }]; }
137
+ const [groupA, groupB] = splitTiles(tiles);
138
+ if (groupB.length === 0) { return [{ tile: groupA[0], ...rect }]; }
139
+ const total = tiles.reduce((sum, tile) => sum + tile.value, 0);
140
+ const weightA = groupA.reduce((sum, tile) => sum + tile.value, 0);
141
+ const ratio = total > 0 ? weightA / total : 0.5;
142
+ if (vertical) {
143
+ const widthA = Math.max(1, Math.min(rect.width - 1, Math.round(rect.width * ratio)));
144
+ return [
145
+ ...layoutTreemap(groupA, { x: rect.x, y: rect.y, width: widthA, height: rect.height }, !vertical),
146
+ ...layoutTreemap(groupB, { x: rect.x + widthA, y: rect.y, width: rect.width - widthA, height: rect.height }, !vertical),
147
+ ];
148
+ }
149
+ const heightA = Math.max(1, Math.min(rect.height - 1, Math.round(rect.height * ratio)));
150
+ return [
151
+ ...layoutTreemap(groupA, { x: rect.x, y: rect.y, width: rect.width, height: heightA }, !vertical),
152
+ ...layoutTreemap(groupB, { x: rect.x, y: rect.y + heightA, width: rect.width, height: rect.height - heightA }, !vertical),
153
+ ];
154
+ }
155
+
156
+ function createGrid(width, height) {
157
+ return Array.from({ length: height }, () => Array.from({ length: width }, () => ({ ch: ' ', kind: null })));
158
+ }
159
+
160
+ function putCell(grid, cell) {
161
+ if (grid[cell.row]?.[cell.col]) {
162
+ grid[cell.row][cell.col] = { ch: cell.ch, kind: cell.kind, label: cell.label ?? false, focused: cell.focused ?? false };
163
+ }
164
+ }
165
+
166
+ const LABEL_FOREGROUND = GIT_CAS_PALETTE.ghost;
167
+ const FOCUS_BORDER_COLOR = GIT_CAS_PALETTE.orange;
168
+
169
+ function outlineGlyphs(focused) {
170
+ return focused ? { h: '═', v: '║', tl: '╔', tr: '╗', bl: '╚', br: '╝' } : { h: '─', v: '│', tl: '┌', tr: '┐', bl: '└', br: '┘' };
171
+ }
172
+
173
+ function outlineRect(grid, rect, focused = false) {
174
+ if (rect.width < 2 || rect.height < 2) { return; }
175
+ const { h, v, tl, tr, bl, br } = outlineGlyphs(focused);
176
+ const top = rect.y; const bottom = rect.y + rect.height - 1; const left = rect.x; const right = rect.x + rect.width - 1;
177
+ for (let col = left + 1; col < right; col++) {
178
+ putCell(grid, { row: top, col, ch: h, kind: rect.tile.kind, focused });
179
+ putCell(grid, { row: bottom, col, ch: h, kind: rect.tile.kind, focused });
180
+ }
181
+ for (let row = top + 1; row < bottom; row++) {
182
+ putCell(grid, { row, col: left, ch: v, kind: rect.tile.kind, focused });
183
+ putCell(grid, { row, col: right, ch: v, kind: rect.tile.kind, focused });
184
+ }
185
+ putCell(grid, { row: top, col: left, ch: tl, kind: rect.tile.kind, focused });
186
+ putCell(grid, { row: top, col: right, ch: tr, kind: rect.tile.kind, focused });
187
+ putCell(grid, { row: bottom, col: left, ch: bl, kind: rect.tile.kind, focused });
188
+ putCell(grid, { row: bottom, col: right, ch: br, kind: rect.tile.kind, focused });
189
+ }
190
+
191
+ function paintLabel(grid, rect) {
192
+ if (rect.width < 6 || rect.height < 2) { return; }
193
+ const label = clip(rect.tile.label, rect.width - 2);
194
+ const labelRow = rect.y + Math.floor((rect.height - 1) / 2);
195
+ const startCol = rect.x + Math.max(0, Math.floor((rect.width - label.length) / 2));
196
+ for (let index = 0; index < label.length; index++) {
197
+ const cell = grid[labelRow]?.[startCol + index];
198
+ if (cell) { grid[labelRow][startCol + index] = { ch: label[index], kind: rect.tile.kind, label: true }; }
199
+ }
200
+ }
201
+
202
+ function paintRect(grid, rect, selectedTileId) {
203
+ const fill = TILE_FILL[rect.tile.kind] ?? TILE_FILL.meta;
204
+ for (let row = rect.y; row < rect.y + rect.height; row++) {
205
+ for (let col = rect.x; col < rect.x + rect.width; col++) {
206
+ if (grid[row]?.[col]) { grid[row][col] = { ch: fill, kind: rect.tile.kind }; }
207
+ }
208
+ }
209
+ outlineRect(grid, rect, rect.tile.id === selectedTileId);
210
+ paintLabel(grid, rect);
211
+ }
212
+
213
+ function renderGrid(grid, ctx) {
214
+ return grid.map((row) => row.map((cell) => {
215
+ if (!cell.kind) { return cell.ch; }
216
+ const color = TILE_COLOR[cell.kind] ?? TILE_COLOR.meta;
217
+ if (cell.focused) {
218
+ const focusText = ctx.style.rgb(FOCUS_BORDER_COLOR[0], FOCUS_BORDER_COLOR[1], FOCUS_BORDER_COLOR[2], cell.ch);
219
+ return ctx.style.inverse ? ctx.style.bold(ctx.style.inverse(focusText)) : ctx.style.bold(focusText);
220
+ }
221
+ if (cell.label) { return ctx.style.bold(ctx.style.rgb(LABEL_FOREGROUND[0], LABEL_FOREGROUND[1], LABEL_FOREGROUND[2], cell.ch)); }
222
+ return ctx.style.rgb(color[0], color[1], color[2], cell.ch);
223
+ }).join(''));
224
+ }
225
+
226
+ function renderLegendLines(ctx, width) {
227
+ return /** @type {Array<keyof typeof TILE_FILL>} */ (['worktree', 'git', 'ref', 'vault', 'cas', 'meta'])
228
+ .map((kind) => {
229
+ const fill = TILE_FILL[kind];
230
+ const color = TILE_COLOR[kind];
231
+ return clip(ctx.style.rgb(color[0], color[1], color[2], `${fill} ${TILE_LABEL[kind]}`), width);
232
+ });
233
+ }
234
+
235
+ function renderDetails(tiles, options) {
236
+ return sortTilesByValue(tiles)
237
+ .slice(0, Math.max(0, options.lines))
238
+ .map((tile, index) => clip(
239
+ `${index + 1}. ${tile.label} [${TILE_LABEL[tile.kind]}] ${formatPercent(tile.value, options.totalValue)} · ${tile.detail}`,
240
+ options.width,
241
+ ));
242
+ }
243
+
244
+ function renderOverview(report, width) {
245
+ const common = [
246
+ clip(`scope ${report.scope}`, width),
247
+ clip(`source ${sourceLabel(report.source)}`, width),
248
+ clip(`level ${currentLevelLabel(report)}`, width),
249
+ clip(`root ${tailClip(report.cwd, Math.max(1, width - 5))}`, width),
250
+ clip(`total ${formatBytes(report.totalValue)}`, width),
251
+ ];
252
+ if (report.scope === 'source') {
253
+ return [
254
+ ...common,
255
+ clip('logical source weighting', width),
256
+ clip(`current regions ${report.tiles.length}`, width),
257
+ clip(`source entries ${report.summary.sourceEntries}`, width),
258
+ clip(`vault entries ${report.summary.vaultEntries}`, width),
259
+ ];
260
+ }
261
+ return [
262
+ ...common,
263
+ clip(`${report.worktreeMode} paths ${report.summary.worktreePaths}`, width),
264
+ clip(`current regions ${report.tiles.length}`, width),
265
+ clip(`worktree regions ${report.summary.worktreeItems}`, width),
266
+ clip(`refs ${report.summary.refCount} in ${report.summary.refNamespaces} namespaces`, width),
267
+ clip(`vault ${report.summary.vaultEntries} source ${report.summary.sourceEntries}`, width),
268
+ ];
269
+ }
270
+
271
+ function selectedTile(report, selectedTileId) {
272
+ if (!selectedTileId) { return report.tiles[0] ?? null; }
273
+ return report.tiles.find((tile) => tile.id === selectedTileId) ?? report.tiles[0] ?? null;
274
+ }
275
+
276
+ function renderFocusedTile(report, selectedTileId, width) {
277
+ const tile = selectedTile(report, selectedTileId);
278
+ if (!tile) { return ['No region selected.']; }
279
+ return [
280
+ clip(tile.label, width),
281
+ clip(`${TILE_LABEL[tile.kind]} · ${formatPercent(tile.value, report.totalValue)}`, width),
282
+ clip(tile.detail, width),
283
+ clip(tile.drillable ? 'Press + to descend.' : 'Leaf tile.', width),
284
+ ];
285
+ }
286
+
287
+ function renderNotes(report, width, lines) {
288
+ return limitLines(report.notes.flatMap((note) => wrapText(note, width)), width, lines);
289
+ }
290
+
291
+ export function renderRepoTreemapMap(report, options) {
292
+ const width = Math.max(12, options.width);
293
+ const height = Math.max(4, options.height);
294
+ const grid = createGrid(width, height);
295
+ const layout = layoutTreemap(sortTilesByValue(report.tiles), { x: 0, y: 0, width, height });
296
+ for (const rect of layout) { paintRect(grid, rect, options.selectedTileId ?? null); }
297
+ return renderGrid(grid, options.ctx).join('\n');
298
+ }
299
+
300
+ export function renderRepoTreemapSidebar(report, options) {
301
+ const width = Math.max(16, options.width);
302
+ return {
303
+ overview: renderOverview(report, width).join('\n'),
304
+ legend: renderLegendLines(options.ctx, width).join('\n'),
305
+ focused: renderFocusedTile(report, options.selectedTileId, width).join('\n'),
306
+ regions: renderDetails(report.tiles, {
307
+ totalValue: report.totalValue,
308
+ width,
309
+ lines: Math.max(3, Math.min(10, options.height - 20)),
310
+ }).join('\n'),
311
+ notes: renderNotes(report, width, Math.max(2, Math.min(8, options.height - 24))).join('\n'),
312
+ };
313
+ }
314
+
315
+ export function renderRepoTreemap(report, options) {
316
+ const width = Math.max(24, options.width); const height = Math.max(10, options.height);
317
+ const summaryLines = renderOverview(report, width); const legendLines = renderLegendLines(options.ctx, width);
318
+ const detailRows = Math.min(4, Math.max(1, height - 10));
319
+ const noteLines = renderNotes(report, width, Math.max(1, height - summaryLines.length - legendLines.length - detailRows - 3));
320
+ const gridHeight = Math.max(4, height - summaryLines.length - legendLines.length - detailRows - noteLines.length - 3);
321
+ return [
322
+ ...summaryLines,
323
+ ...renderRepoTreemapMap(report, { ...options, width, height: gridHeight }).split('\n'),
324
+ ...legendLines,
325
+ ...renderDetails(report.tiles, { totalValue: report.totalValue, width, lines: detailRows }),
326
+ ...noteLines,
327
+ ].slice(0, height).join('\n');
328
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Bak-Sneppen SOC model shader for the title screen.
3
+ * Optimized via internal rasterization to handle high species counts at 60fps.
4
+ */
5
+
6
+ let currentNumSpecies = 120;
7
+ let fitnessState = new Float32Array(currentNumSpecies);
8
+ let initialized = false;
9
+ let lastSimTime = -1;
10
+
11
+ // Backing buffer for rasterized sub-pixels
12
+ let frameBuffer = new Int32Array(0);
13
+ let bufferW = 0;
14
+ let bufferH = 0;
15
+
16
+ // Convert hex string to integer for faster buffer storage
17
+ function hexToInt(hex) {
18
+ return parseInt(hex.replace('#', ''), 16);
19
+ }
20
+
21
+ const BG_INT = hexToInt('#1d252b');
22
+ const DR_INT = hexToInt('#fbfcfc');
23
+ const STEM_INT = hexToInt('#FF8552');
24
+ const HEAD_INT = hexToInt('#07BEB8');
25
+ const INT_TO_HEX = {
26
+ [BG_INT]: '#1d252b',
27
+ [DR_INT]: '#fbfcfc',
28
+ [STEM_INT]: '#FF8552',
29
+ [HEAD_INT]: '#07BEB8'
30
+ };
31
+
32
+ function initBakSneppen(numSpecies) {
33
+ currentNumSpecies = numSpecies;
34
+ fitnessState = new Float32Array(currentNumSpecies);
35
+ for (let i = 0; i < currentNumSpecies; i++) {
36
+ fitnessState[i] = Math.random();
37
+ }
38
+ initialized = true;
39
+ }
40
+
41
+ function stepBakSneppen(steps) {
42
+ for (let s = 0; s < steps; s++) {
43
+ let minIdx = 0;
44
+ let minVal = fitnessState[0];
45
+ for (let i = 1; i < currentNumSpecies; i++) {
46
+ if (fitnessState[i] < minVal) {
47
+ minVal = fitnessState[i];
48
+ minIdx = i;
49
+ }
50
+ }
51
+ const leftIdx = (minIdx - 1 + currentNumSpecies) % currentNumSpecies;
52
+ const rightIdx = (minIdx + 1) % currentNumSpecies;
53
+ fitnessState[leftIdx] = Math.random();
54
+ fitnessState[minIdx] = Math.random();
55
+ fitnessState[rightIdx] = Math.random();
56
+ }
57
+ }
58
+
59
+ function project3D({ x, y, z, elevation, azimuth }) {
60
+ const el = elevation * (Math.PI / 180);
61
+ const az = azimuth * (Math.PI / 180);
62
+ const x1 = x * Math.cos(az) - y * Math.sin(az);
63
+ const y1 = x * Math.sin(az) + y * Math.cos(az);
64
+ const y2 = y1 * Math.cos(el) - z * Math.sin(el);
65
+ const z2 = y1 * Math.sin(el) + z * Math.cos(el);
66
+ return { px: x1, py: y2, pz: z2 };
67
+ }
68
+
69
+ function mapToBuffer(x, y) {
70
+ const ix = Math.round(((x / 1.6) + 1) * 0.5 * (bufferW - 1));
71
+ const iy = Math.round(((y / 1.2) + 1) * 0.5 * (bufferH - 1));
72
+ return { ix, iy };
73
+ }
74
+
75
+ function setBufferPixel(x, y, color) {
76
+ if (x < 0 || x >= bufferW || y < 0 || y >= bufferH) {
77
+ return;
78
+ }
79
+ frameBuffer[y * bufferW + x] = color;
80
+ }
81
+
82
+ function drawLine({ x0, y0, x1, y1, color }) {
83
+ const p0 = mapToBuffer(x0, y0);
84
+ const p1 = mapToBuffer(x1, y1);
85
+ const dx = Math.abs(p1.ix - p0.ix);
86
+ const dy = -Math.abs(p1.iy - p0.iy);
87
+ const sx = p0.ix < p1.ix ? 1 : -1;
88
+ const sy = p0.iy < p1.iy ? 1 : -1;
89
+ let err = dx + dy;
90
+ let cx = p0.ix;
91
+ let cy = p0.iy;
92
+
93
+ while (true) {
94
+ setBufferPixel(cx, cy, color);
95
+ if (cx === p1.ix && cy === p1.iy) {
96
+ break;
97
+ }
98
+ const e2 = 2 * err;
99
+ if (e2 >= dy) {
100
+ err += dy;
101
+ cx += sx;
102
+ }
103
+ if (e2 <= dx) {
104
+ err += dx;
105
+ cy += sy;
106
+ }
107
+ }
108
+ }
109
+
110
+ function drawPoint({ x, y, color, radius = 1 }) {
111
+ const ix = Math.round(((x / 1.6) + 1) * 0.5 * (bufferW - 1));
112
+ const iy = Math.round(((y / 1.2) + 1) * 0.5 * (bufferH - 1));
113
+
114
+ for (let dy = -radius; dy <= radius; dy++) {
115
+ for (let dx = -radius; dx <= radius; dx++) {
116
+ const cx = ix + dx;
117
+ const cy = iy + dy;
118
+ if (cx >= 0 && cx < bufferW && cy >= 0 && cy < bufferH) {
119
+ frameBuffer[cy * bufferW + cx] = color;
120
+ }
121
+ }
122
+ }
123
+ }
124
+
125
+ function rasterizeFrame(time) {
126
+ frameBuffer.fill(BG_INT);
127
+ const elevation = 35;
128
+ const azimuth = 45 + (time * 15);
129
+
130
+ for (let i = 0; i < currentNumSpecies; i++) {
131
+ const theta = (i / currentNumSpecies) * 2 * Math.PI + (time * 0.5);
132
+ const baseProj = project3D({ x: Math.cos(theta), y: Math.sin(theta), z: 0, elevation, azimuth });
133
+ const headProj = project3D({ x: Math.cos(theta), y: Math.sin(theta), z: fitnessState[i], elevation, azimuth });
134
+
135
+ drawLine({ x0: baseProj.px, y0: baseProj.py, x1: headProj.px, y1: headProj.py, color: STEM_INT });
136
+
137
+ const nextTheta = ((i + 1) / currentNumSpecies) * 2 * Math.PI + (time * 0.5);
138
+ const nextBaseProj = project3D({ x: Math.cos(nextTheta), y: Math.sin(nextTheta), z: 0, elevation, azimuth });
139
+ drawLine({ x0: baseProj.px, y0: baseProj.py, x1: nextBaseProj.px, y1: nextBaseProj.py, color: DR_INT });
140
+
141
+ drawPoint({ x: headProj.px, y: headProj.py, color: HEAD_INT });
142
+ }
143
+ }
144
+
145
+ function updateFrameBuffer(time, uniforms) {
146
+ const tw = (uniforms?.width ?? 80) * 2;
147
+ const th = (uniforms?.height ?? 24) * 2;
148
+
149
+ if (tw !== bufferW || th !== bufferH) {
150
+ bufferW = tw;
151
+ bufferH = th;
152
+ frameBuffer = new Int32Array(bufferW * bufferH);
153
+ lastSimTime = -1;
154
+ }
155
+
156
+ if (time !== lastSimTime) {
157
+ stepBakSneppen(3);
158
+ rasterizeFrame(time);
159
+ lastSimTime = time;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * @param {import('@flyingrobots/bijou-tui').ShaderParams} params
165
+ * @returns {import('@flyingrobots/bijou').Cell}
166
+ */
167
+ export function bakSneppenShader({ u, v, time, uniforms }) {
168
+ const targetNumSpecies = Math.max(50, Math.min(300, uniforms?.entryCount ?? 120));
169
+ if (!initialized || currentNumSpecies !== targetNumSpecies) {
170
+ initBakSneppen(targetNumSpecies);
171
+ }
172
+
173
+ updateFrameBuffer(time, uniforms);
174
+
175
+ const colorInt = frameBuffer[Math.floor(v * (bufferH - 1)) * bufferW + Math.floor(u * (bufferW - 1))];
176
+ if (colorInt !== BG_INT) {
177
+ return { char: '█', fg: INT_TO_HEX[colorInt], bg: '#1d252b' };
178
+ }
179
+ return { char: ' ', bg: '#1d252b' };
180
+ }