stellavault 0.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.
Files changed (294) hide show
  1. package/.env.example +12 -0
  2. package/CLAUDE.md +39 -0
  3. package/CONTRIBUTING.md +65 -0
  4. package/LICENSE +21 -0
  5. package/README.md +182 -0
  6. package/memory/MEMORY.md +25 -0
  7. package/package.json +33 -0
  8. package/packages/cli/bin/ekh.js +2 -0
  9. package/packages/cli/bin/stellavault.js +2 -0
  10. package/packages/cli/dist/commands/brief-cmd.d.ts +2 -0
  11. package/packages/cli/dist/commands/brief-cmd.d.ts.map +1 -0
  12. package/packages/cli/dist/commands/brief-cmd.js +82 -0
  13. package/packages/cli/dist/commands/brief-cmd.js.map +1 -0
  14. package/packages/cli/dist/commands/capture-cmd.d.ts +7 -0
  15. package/packages/cli/dist/commands/capture-cmd.d.ts.map +1 -0
  16. package/packages/cli/dist/commands/capture-cmd.js +31 -0
  17. package/packages/cli/dist/commands/capture-cmd.js.map +1 -0
  18. package/packages/cli/dist/commands/card-cmd.d.ts +4 -0
  19. package/packages/cli/dist/commands/card-cmd.d.ts.map +1 -0
  20. package/packages/cli/dist/commands/card-cmd.js +26 -0
  21. package/packages/cli/dist/commands/card-cmd.js.map +1 -0
  22. package/packages/cli/dist/commands/clip-cmd.d.ts +4 -0
  23. package/packages/cli/dist/commands/clip-cmd.d.ts.map +1 -0
  24. package/packages/cli/dist/commands/clip-cmd.js +151 -0
  25. package/packages/cli/dist/commands/clip-cmd.js.map +1 -0
  26. package/packages/cli/dist/commands/cloud-cmd.d.ts +4 -0
  27. package/packages/cli/dist/commands/cloud-cmd.d.ts.map +1 -0
  28. package/packages/cli/dist/commands/cloud-cmd.js +64 -0
  29. package/packages/cli/dist/commands/cloud-cmd.js.map +1 -0
  30. package/packages/cli/dist/commands/contradictions-cmd.d.ts +2 -0
  31. package/packages/cli/dist/commands/contradictions-cmd.d.ts.map +1 -0
  32. package/packages/cli/dist/commands/contradictions-cmd.js +34 -0
  33. package/packages/cli/dist/commands/contradictions-cmd.js.map +1 -0
  34. package/packages/cli/dist/commands/decay-cmd.d.ts +2 -0
  35. package/packages/cli/dist/commands/decay-cmd.d.ts.map +1 -0
  36. package/packages/cli/dist/commands/decay-cmd.js +48 -0
  37. package/packages/cli/dist/commands/decay-cmd.js.map +1 -0
  38. package/packages/cli/dist/commands/digest-cmd.d.ts +4 -0
  39. package/packages/cli/dist/commands/digest-cmd.d.ts.map +1 -0
  40. package/packages/cli/dist/commands/digest-cmd.js +79 -0
  41. package/packages/cli/dist/commands/digest-cmd.js.map +1 -0
  42. package/packages/cli/dist/commands/duplicates-cmd.d.ts +4 -0
  43. package/packages/cli/dist/commands/duplicates-cmd.d.ts.map +1 -0
  44. package/packages/cli/dist/commands/duplicates-cmd.js +30 -0
  45. package/packages/cli/dist/commands/duplicates-cmd.js.map +1 -0
  46. package/packages/cli/dist/commands/federate-cmd.d.ts +5 -0
  47. package/packages/cli/dist/commands/federate-cmd.d.ts.map +1 -0
  48. package/packages/cli/dist/commands/federate-cmd.js +217 -0
  49. package/packages/cli/dist/commands/federate-cmd.js.map +1 -0
  50. package/packages/cli/dist/commands/gaps-cmd.d.ts +2 -0
  51. package/packages/cli/dist/commands/gaps-cmd.d.ts.map +1 -0
  52. package/packages/cli/dist/commands/gaps-cmd.js +33 -0
  53. package/packages/cli/dist/commands/gaps-cmd.js.map +1 -0
  54. package/packages/cli/dist/commands/graph-cmd.d.ts +2 -0
  55. package/packages/cli/dist/commands/graph-cmd.d.ts.map +1 -0
  56. package/packages/cli/dist/commands/graph-cmd.js +77 -0
  57. package/packages/cli/dist/commands/graph-cmd.js.map +1 -0
  58. package/packages/cli/dist/commands/index-cmd.d.ts +2 -0
  59. package/packages/cli/dist/commands/index-cmd.d.ts.map +1 -0
  60. package/packages/cli/dist/commands/index-cmd.js +57 -0
  61. package/packages/cli/dist/commands/index-cmd.js.map +1 -0
  62. package/packages/cli/dist/commands/init-cmd.d.ts +2 -0
  63. package/packages/cli/dist/commands/init-cmd.d.ts.map +1 -0
  64. package/packages/cli/dist/commands/init-cmd.js +123 -0
  65. package/packages/cli/dist/commands/init-cmd.js.map +1 -0
  66. package/packages/cli/dist/commands/learn-cmd.d.ts +2 -0
  67. package/packages/cli/dist/commands/learn-cmd.d.ts.map +1 -0
  68. package/packages/cli/dist/commands/learn-cmd.js +48 -0
  69. package/packages/cli/dist/commands/learn-cmd.js.map +1 -0
  70. package/packages/cli/dist/commands/pack-cmd.d.ts +15 -0
  71. package/packages/cli/dist/commands/pack-cmd.d.ts.map +1 -0
  72. package/packages/cli/dist/commands/pack-cmd.js +93 -0
  73. package/packages/cli/dist/commands/pack-cmd.js.map +1 -0
  74. package/packages/cli/dist/commands/review-cmd.d.ts +4 -0
  75. package/packages/cli/dist/commands/review-cmd.d.ts.map +1 -0
  76. package/packages/cli/dist/commands/review-cmd.js +107 -0
  77. package/packages/cli/dist/commands/review-cmd.js.map +1 -0
  78. package/packages/cli/dist/commands/search-cmd.d.ts +4 -0
  79. package/packages/cli/dist/commands/search-cmd.d.ts.map +1 -0
  80. package/packages/cli/dist/commands/search-cmd.js +38 -0
  81. package/packages/cli/dist/commands/search-cmd.js.map +1 -0
  82. package/packages/cli/dist/commands/serve-cmd.d.ts +2 -0
  83. package/packages/cli/dist/commands/serve-cmd.d.ts.map +1 -0
  84. package/packages/cli/dist/commands/serve-cmd.js +14 -0
  85. package/packages/cli/dist/commands/serve-cmd.js.map +1 -0
  86. package/packages/cli/dist/commands/status-cmd.d.ts +2 -0
  87. package/packages/cli/dist/commands/status-cmd.d.ts.map +1 -0
  88. package/packages/cli/dist/commands/status-cmd.js +33 -0
  89. package/packages/cli/dist/commands/status-cmd.js.map +1 -0
  90. package/packages/cli/dist/commands/sync-cmd.d.ts +5 -0
  91. package/packages/cli/dist/commands/sync-cmd.d.ts.map +1 -0
  92. package/packages/cli/dist/commands/sync-cmd.js +62 -0
  93. package/packages/cli/dist/commands/sync-cmd.js.map +1 -0
  94. package/packages/cli/dist/commands/vault-cmd.d.ts +10 -0
  95. package/packages/cli/dist/commands/vault-cmd.d.ts.map +1 -0
  96. package/packages/cli/dist/commands/vault-cmd.js +54 -0
  97. package/packages/cli/dist/commands/vault-cmd.js.map +1 -0
  98. package/packages/cli/dist/index.d.ts +2 -0
  99. package/packages/cli/dist/index.d.ts.map +1 -0
  100. package/packages/cli/dist/index.js +156 -0
  101. package/packages/cli/dist/index.js.map +1 -0
  102. package/packages/cli/package.json +24 -0
  103. package/packages/cli/src/commands/brief-cmd.ts +87 -0
  104. package/packages/cli/src/commands/capture-cmd.ts +34 -0
  105. package/packages/cli/src/commands/card-cmd.ts +29 -0
  106. package/packages/cli/src/commands/clip-cmd.ts +172 -0
  107. package/packages/cli/src/commands/cloud-cmd.ts +75 -0
  108. package/packages/cli/src/commands/contradictions-cmd.ts +41 -0
  109. package/packages/cli/src/commands/decay-cmd.ts +57 -0
  110. package/packages/cli/src/commands/digest-cmd.ts +89 -0
  111. package/packages/cli/src/commands/duplicates-cmd.ts +38 -0
  112. package/packages/cli/src/commands/federate-cmd.ts +236 -0
  113. package/packages/cli/src/commands/gaps-cmd.ts +40 -0
  114. package/packages/cli/src/commands/graph-cmd.ts +88 -0
  115. package/packages/cli/src/commands/index-cmd.ts +65 -0
  116. package/packages/cli/src/commands/init-cmd.ts +145 -0
  117. package/packages/cli/src/commands/learn-cmd.ts +56 -0
  118. package/packages/cli/src/commands/pack-cmd.ts +121 -0
  119. package/packages/cli/src/commands/review-cmd.ts +125 -0
  120. package/packages/cli/src/commands/search-cmd.ts +45 -0
  121. package/packages/cli/src/commands/serve-cmd.ts +17 -0
  122. package/packages/cli/src/commands/status-cmd.ts +37 -0
  123. package/packages/cli/src/commands/sync-cmd.ts +68 -0
  124. package/packages/cli/src/commands/vault-cmd.ts +64 -0
  125. package/packages/cli/src/index.ts +187 -0
  126. package/packages/core/package.json +40 -0
  127. package/packages/core/src/api/dashboard.ts +138 -0
  128. package/packages/core/src/api/graph-data.ts +286 -0
  129. package/packages/core/src/api/pwa.ts +82 -0
  130. package/packages/core/src/api/server.ts +660 -0
  131. package/packages/core/src/capture/voice.ts +168 -0
  132. package/packages/core/src/cloud/index.ts +2 -0
  133. package/packages/core/src/cloud/sync.ts +167 -0
  134. package/packages/core/src/config.ts +82 -0
  135. package/packages/core/src/federation/credits.ts +80 -0
  136. package/packages/core/src/federation/hyperswarm.d.ts +19 -0
  137. package/packages/core/src/federation/identity.ts +90 -0
  138. package/packages/core/src/federation/index.ts +8 -0
  139. package/packages/core/src/federation/node.ts +235 -0
  140. package/packages/core/src/federation/privacy.ts +52 -0
  141. package/packages/core/src/federation/reputation.ts +202 -0
  142. package/packages/core/src/federation/search.ts +129 -0
  143. package/packages/core/src/federation/sharing.ts +165 -0
  144. package/packages/core/src/federation/trust.ts +76 -0
  145. package/packages/core/src/federation/types.ts +25 -0
  146. package/packages/core/src/i18n/index.ts +85 -0
  147. package/packages/core/src/index.ts +133 -0
  148. package/packages/core/src/indexer/chunker.ts +180 -0
  149. package/packages/core/src/indexer/embedder.ts +9 -0
  150. package/packages/core/src/indexer/index.ts +113 -0
  151. package/packages/core/src/indexer/local-embedder.ts +35 -0
  152. package/packages/core/src/indexer/scanner.ts +142 -0
  153. package/packages/core/src/indexer/watcher.ts +62 -0
  154. package/packages/core/src/intelligence/contradiction-detector.ts +134 -0
  155. package/packages/core/src/intelligence/decay-engine.ts +229 -0
  156. package/packages/core/src/intelligence/duplicate-detector.ts +71 -0
  157. package/packages/core/src/intelligence/fsrs.ts +79 -0
  158. package/packages/core/src/intelligence/gap-detector.ts +109 -0
  159. package/packages/core/src/intelligence/learning-path.ts +86 -0
  160. package/packages/core/src/intelligence/notifications.ts +106 -0
  161. package/packages/core/src/intelligence/predictive-gaps.ts +94 -0
  162. package/packages/core/src/intelligence/semantic-versioning.ts +97 -0
  163. package/packages/core/src/intelligence/types.ts +28 -0
  164. package/packages/core/src/mcp/custom-tools.ts +97 -0
  165. package/packages/core/src/mcp/index.ts +1 -0
  166. package/packages/core/src/mcp/server.ts +142 -0
  167. package/packages/core/src/mcp/tools/agentic-graph.ts +96 -0
  168. package/packages/core/src/mcp/tools/brief.ts +49 -0
  169. package/packages/core/src/mcp/tools/decay.ts +40 -0
  170. package/packages/core/src/mcp/tools/decision-journal.ts +95 -0
  171. package/packages/core/src/mcp/tools/export.ts +72 -0
  172. package/packages/core/src/mcp/tools/federated-search.ts +43 -0
  173. package/packages/core/src/mcp/tools/generate-claude-md.ts +130 -0
  174. package/packages/core/src/mcp/tools/get-document.ts +26 -0
  175. package/packages/core/src/mcp/tools/get-related.ts +41 -0
  176. package/packages/core/src/mcp/tools/learning-path.ts +52 -0
  177. package/packages/core/src/mcp/tools/list-topics.ts +20 -0
  178. package/packages/core/src/mcp/tools/search.ts +35 -0
  179. package/packages/core/src/mcp/tools/snapshot.ts +98 -0
  180. package/packages/core/src/multi-vault/index.ts +118 -0
  181. package/packages/core/src/pack/creator.ts +127 -0
  182. package/packages/core/src/pack/exporter.ts +21 -0
  183. package/packages/core/src/pack/importer.ts +82 -0
  184. package/packages/core/src/pack/index.ts +5 -0
  185. package/packages/core/src/pack/marketplace.ts +103 -0
  186. package/packages/core/src/pack/pii-masker.ts +38 -0
  187. package/packages/core/src/pack/types.ts +39 -0
  188. package/packages/core/src/plugins/index.ts +100 -0
  189. package/packages/core/src/plugins/webhooks.ts +110 -0
  190. package/packages/core/src/search/bm25.ts +16 -0
  191. package/packages/core/src/search/index.ts +83 -0
  192. package/packages/core/src/search/rrf.ts +31 -0
  193. package/packages/core/src/search/semantic.ts +15 -0
  194. package/packages/core/src/store/index.ts +2 -0
  195. package/packages/core/src/store/sqlite-vec.ts +290 -0
  196. package/packages/core/src/store/types.ts +22 -0
  197. package/packages/core/src/team/index.ts +126 -0
  198. package/packages/core/src/types/chunk.ts +25 -0
  199. package/packages/core/src/types/document.ts +24 -0
  200. package/packages/core/src/types/graph.ts +44 -0
  201. package/packages/core/src/types/index.ts +15 -0
  202. package/packages/core/src/types/search.ts +38 -0
  203. package/packages/core/src/utils/retry.ts +85 -0
  204. package/packages/core/tests/api-card.test.ts +60 -0
  205. package/packages/core/tests/api-routes.test.ts +98 -0
  206. package/packages/core/tests/bm25.test.ts +87 -0
  207. package/packages/core/tests/chunker.test.ts +48 -0
  208. package/packages/core/tests/cluster.test.ts +75 -0
  209. package/packages/core/tests/constellation.test.ts +77 -0
  210. package/packages/core/tests/export-utils.test.ts +97 -0
  211. package/packages/core/tests/fsrs.test.ts +96 -0
  212. package/packages/core/tests/gesture-detector.test.ts +45 -0
  213. package/packages/core/tests/graph-data.test.ts +87 -0
  214. package/packages/core/tests/layout.test.ts +83 -0
  215. package/packages/core/tests/mcp.test.ts +148 -0
  216. package/packages/core/tests/pack.test.ts +127 -0
  217. package/packages/core/tests/pii-masker.test.ts +42 -0
  218. package/packages/core/tests/profile-card.test.ts +62 -0
  219. package/packages/core/tests/rrf.test.ts +29 -0
  220. package/packages/core/tests/search-integration.test.ts +139 -0
  221. package/packages/core/tests/store.test.ts +80 -0
  222. package/packages/graph/click-result.png +0 -0
  223. package/packages/graph/index.html +17 -0
  224. package/packages/graph/package.json +32 -0
  225. package/packages/graph/src/App.tsx +7 -0
  226. package/packages/graph/src/api/client.ts +39 -0
  227. package/packages/graph/src/components/ClusterFilter.tsx +73 -0
  228. package/packages/graph/src/components/ConstellationView.tsx +232 -0
  229. package/packages/graph/src/components/ExportPanel.tsx +177 -0
  230. package/packages/graph/src/components/Graph3D.tsx +230 -0
  231. package/packages/graph/src/components/GraphEdges.tsx +100 -0
  232. package/packages/graph/src/components/GraphNodes.tsx +386 -0
  233. package/packages/graph/src/components/HealthDashboard.tsx +173 -0
  234. package/packages/graph/src/components/Layout.tsx +214 -0
  235. package/packages/graph/src/components/MotionOverlay.tsx +81 -0
  236. package/packages/graph/src/components/MotionToggle.tsx +33 -0
  237. package/packages/graph/src/components/MultiverseView.tsx +286 -0
  238. package/packages/graph/src/components/NodeDetail.tsx +232 -0
  239. package/packages/graph/src/components/PulseParticle.tsx +232 -0
  240. package/packages/graph/src/components/SearchBar.tsx +107 -0
  241. package/packages/graph/src/components/StarField.tsx +197 -0
  242. package/packages/graph/src/components/StatusBar.tsx +53 -0
  243. package/packages/graph/src/components/Timeline.tsx +148 -0
  244. package/packages/graph/src/components/ToolsPanel.tsx +512 -0
  245. package/packages/graph/src/components/Tooltip.tsx +100 -0
  246. package/packages/graph/src/components/TypeFilter.tsx +131 -0
  247. package/packages/graph/src/embed/EmbedGraph.tsx +144 -0
  248. package/packages/graph/src/hooks/useConstellationLOD.ts +76 -0
  249. package/packages/graph/src/hooks/useDecay.ts +37 -0
  250. package/packages/graph/src/hooks/useExport.ts +165 -0
  251. package/packages/graph/src/hooks/useGraph.ts +69 -0
  252. package/packages/graph/src/hooks/useKeyboardNav.ts +122 -0
  253. package/packages/graph/src/hooks/useLayout.ts +45 -0
  254. package/packages/graph/src/hooks/useMotion.ts +120 -0
  255. package/packages/graph/src/hooks/usePulse.ts +58 -0
  256. package/packages/graph/src/hooks/useSearch.ts +71 -0
  257. package/packages/graph/src/lib/constellation.ts +107 -0
  258. package/packages/graph/src/lib/export-utils.ts +48 -0
  259. package/packages/graph/src/lib/gesture-detector.ts +123 -0
  260. package/packages/graph/src/lib/layout.worker.ts +153 -0
  261. package/packages/graph/src/lib/motion-controller.ts +83 -0
  262. package/packages/graph/src/lib/profile-card.ts +122 -0
  263. package/packages/graph/src/main.tsx +4 -0
  264. package/packages/graph/src/stores/graph-store.ts +155 -0
  265. package/packages/graph/success.png +0 -0
  266. package/packages/graph/test-click.mjs +49 -0
  267. package/packages/graph/test-explore.mjs +102 -0
  268. package/packages/graph/test-final.mjs +61 -0
  269. package/packages/graph/test-graph.mjs +139 -0
  270. package/packages/graph/test-hover.mjs +48 -0
  271. package/packages/graph/test-pulse.mjs +68 -0
  272. package/packages/graph/test-screenshot.mjs +56 -0
  273. package/packages/graph/test-v2.mjs +97 -0
  274. package/packages/graph/vite.config.ts +15 -0
  275. package/packages/sync/.env.example +11 -0
  276. package/packages/sync/.sync-state.json +317 -0
  277. package/packages/sync/.upload-state.json +1009 -0
  278. package/packages/sync/create-stella-network-notion.mjs +151 -0
  279. package/packages/sync/create-stellavault-project-notion.mjs +322 -0
  280. package/packages/sync/logs/sync-2026-03-28.log +6 -0
  281. package/packages/sync/logs/sync-2026-03-29.log +12 -0
  282. package/packages/sync/logs/sync-2026-03-30.log +6 -0
  283. package/packages/sync/logs/sync-2026-03-31.log +6 -0
  284. package/packages/sync/logs/sync-2026-04-01.log +6 -0
  285. package/packages/sync/logs/sync-2026-04-02.log +6 -0
  286. package/packages/sync/package-lock.json +373 -0
  287. package/packages/sync/package.json +16 -0
  288. package/packages/sync/run-sync.bat +18 -0
  289. package/packages/sync/run-sync.mjs +46 -0
  290. package/packages/sync/setup-scheduler.mjs +119 -0
  291. package/packages/sync/structured-sync.mjs +187 -0
  292. package/packages/sync/sync-to-obsidian.mjs +264 -0
  293. package/packages/sync/upload-pdca-to-notion.mjs +495 -0
  294. package/tsconfig.base.json +18 -0
@@ -0,0 +1,187 @@
1
+ import { Command } from 'commander';
2
+ import { indexCommand } from './commands/index-cmd.js';
3
+ import { searchCommand } from './commands/search-cmd.js';
4
+ import { serveCommand } from './commands/serve-cmd.js';
5
+ import { statusCommand } from './commands/status-cmd.js';
6
+ import { graphCommand } from './commands/graph-cmd.js';
7
+ import { cardCommand } from './commands/card-cmd.js';
8
+ import { packCreateCommand, packExportCommand, packImportCommand, packListCommand, packInfoCommand } from './commands/pack-cmd.js';
9
+ import { decayCommand } from './commands/decay-cmd.js';
10
+ import { syncCommand } from './commands/sync-cmd.js';
11
+ import { reviewCommand } from './commands/review-cmd.js';
12
+ import { duplicatesCommand } from './commands/duplicates-cmd.js';
13
+ import { gapsCommand } from './commands/gaps-cmd.js';
14
+ import { clipCommand } from './commands/clip-cmd.js';
15
+ import { briefCommand } from './commands/brief-cmd.js';
16
+ import { digestCommand } from './commands/digest-cmd.js';
17
+ import { initCommand } from './commands/init-cmd.js';
18
+ import { learnCommand } from './commands/learn-cmd.js';
19
+ import { contradictionsCommand } from './commands/contradictions-cmd.js';
20
+ import { federateJoinCommand, federateStatusCommand } from './commands/federate-cmd.js';
21
+ import { cloudSyncCommand, cloudRestoreCommand, cloudStatusCommand } from './commands/cloud-cmd.js';
22
+ import { vaultAddCommand, vaultListCommand, vaultRemoveCommand, vaultSearchAllCommand } from './commands/vault-cmd.js';
23
+ import { captureCommand } from './commands/capture-cmd.js';
24
+
25
+ const program = new Command();
26
+
27
+ program
28
+ .name('stellavault')
29
+ .description('Stellavault — Turn your Obsidian vault into a 3D neural knowledge graph')
30
+ .version('0.1.0')
31
+ .option('--json', 'Output in JSON format (for scripting)')
32
+ .option('--quiet', 'Suppress non-essential output');
33
+
34
+ program
35
+ .command('init')
36
+ .description('Interactive setup wizard — get started in 3 minutes')
37
+ .action(initCommand);
38
+
39
+ program
40
+ .command('index [vault-path]')
41
+ .description('Obsidian vault를 벡터화하여 인덱싱합니다')
42
+ .action(indexCommand);
43
+
44
+ program
45
+ .command('search <query>')
46
+ .description('지식 베이스에서 검색합니다')
47
+ .option('-l, --limit <n>', '결과 수', '5')
48
+ .action(searchCommand);
49
+
50
+ program
51
+ .command('serve')
52
+ .description('MCP 서버를 시작합니다 (Claude Code 연동)')
53
+ .action(serveCommand);
54
+
55
+ program
56
+ .command('status')
57
+ .description('인덱스 상태를 확인합니다')
58
+ .action(statusCommand);
59
+
60
+ program
61
+ .command('graph')
62
+ .description('3D Knowledge Graph API 서버를 시작합니다')
63
+ .action(graphCommand);
64
+
65
+ program
66
+ .command('card')
67
+ .description('SVG 프로필 카드를 생성합니다')
68
+ .option('-o, --output <path>', '출력 파일 경로', 'knowledge-card.svg')
69
+ .action(cardCommand);
70
+
71
+ program
72
+ .command('learn')
73
+ .description('AI learning path — personalized recommendations based on decay + gaps')
74
+ .action(learnCommand);
75
+
76
+ program
77
+ .command('contradictions')
78
+ .description('Detect contradicting statements across your notes')
79
+ .action(contradictionsCommand);
80
+
81
+ program
82
+ .command('decay')
83
+ .description('지식 감쇠 리포트를 출력합니다 (잊어가는 노트 확인)')
84
+ .action(decayCommand);
85
+
86
+ program
87
+ .command('brief')
88
+ .description('오늘의 지식 브리핑 (감쇠 + 갭 + 활동 요약)')
89
+ .action(briefCommand);
90
+
91
+ program
92
+ .command('digest')
93
+ .description('주간 지식 활동 리포트')
94
+ .option('-d, --days <n>', '기간 (일)', '7')
95
+ .action(digestCommand);
96
+
97
+ program
98
+ .command('clip <url>')
99
+ .description('웹 페이지/YouTube를 Obsidian에 클리핑')
100
+ .option('-f, --folder <path>', 'vault 내 저장 폴더', '06_Research/clips')
101
+ .action(clipCommand);
102
+
103
+ program
104
+ .command('gaps')
105
+ .description('지식 갭을 탐지합니다 (클러스터 간 연결 부족 영역)')
106
+ .action(gapsCommand);
107
+
108
+ program
109
+ .command('duplicates')
110
+ .description('중복/유사 노트를 탐지합니다')
111
+ .option('-t, --threshold <n>', '유사도 임계값 (0~1)', '0.88')
112
+ .action(duplicatesCommand);
113
+
114
+ program
115
+ .command('review')
116
+ .description('일일 지식 리뷰 — 잊어가는 노트를 Obsidian에서 열어 리뷰')
117
+ .option('-n, --count <n>', '리뷰할 노트 수', '5')
118
+ .action(reviewCommand);
119
+
120
+ program
121
+ .command('sync')
122
+ .description('Notion → Obsidian 동기화')
123
+ .option('--upload', 'PDCA 문서를 Notion에 업로드')
124
+ .option('--watch', '5분 간격 자동 동기화')
125
+ .action(syncCommand);
126
+
127
+ const federate = program.command('federate').description('Federation — P2P knowledge network');
128
+
129
+ federate.command('join')
130
+ .description('Join the federation network (interactive mode)')
131
+ .option('-n, --name <name>', 'Display name for this node')
132
+ .action(federateJoinCommand);
133
+
134
+ federate.command('status')
135
+ .description('Show federation identity and status')
136
+ .action(federateStatusCommand);
137
+
138
+ program
139
+ .command('capture <audio-file>')
140
+ .description('Voice capture — transcribe audio to knowledge note (requires Whisper)')
141
+ .option('-m, --model <model>', 'Whisper model (tiny/base/small/medium/large)', 'base')
142
+ .option('-l, --language <lang>', 'Language (auto-detect if omitted)')
143
+ .option('-t, --tags <tags>', 'Comma-separated tags')
144
+ .option('-f, --folder <folder>', 'Vault subfolder', '01_Knowledge/voice')
145
+ .action(captureCommand);
146
+
147
+ const vault = program.command('vault').description('Multi-Vault — manage and search across vaults');
148
+ vault.command('add <id> <path>').description('Register a vault').option('-n, --name <name>', 'Display name').option('-s, --shared', 'Allow federation sharing').action(vaultAddCommand);
149
+ vault.command('list').description('List registered vaults').action(vaultListCommand);
150
+ vault.command('remove <id>').description('Unregister a vault').action(vaultRemoveCommand);
151
+ vault.command('search-all <query>').description('Search across all registered vaults').option('-l, --limit <n>', 'Max results', '10').action(vaultSearchAllCommand);
152
+
153
+ const cloud = program.command('cloud').description('Cloud — E2E encrypted backup');
154
+ cloud.command('sync').description('Upload encrypted DB to cloud').action(cloudSyncCommand);
155
+ cloud.command('restore').description('Download and decrypt DB from cloud').action(cloudRestoreCommand);
156
+ cloud.command('status').description('Show last sync status').action(cloudStatusCommand);
157
+
158
+ const pack = program.command('pack').description('Knowledge Pack 관리');
159
+
160
+ pack.command('create <name>')
161
+ .description('검색/클러스터 기반 Knowledge Pack 생성')
162
+ .option('--from-search <query>', '검색 쿼리에서 생성')
163
+ .option('--from-cluster <id>', '클러스터 ID에서 생성')
164
+ .option('--author <name>', '작성자', 'anonymous')
165
+ .option('--license <license>', '라이선스', 'CC-BY-4.0')
166
+ .option('--description <desc>', '설명')
167
+ .option('--limit <n>', '최대 청크 수', '100')
168
+ .action(packCreateCommand);
169
+
170
+ pack.command('export <name>')
171
+ .description('.sv-pack 파일로 내보내기')
172
+ .option('-o, --output <path>', '출력 경로')
173
+ .action(packExportCommand);
174
+
175
+ pack.command('import <file>')
176
+ .description('.sv-pack 파일 가져오기 → 벡터 DB 병합')
177
+ .action(packImportCommand);
178
+
179
+ pack.command('list')
180
+ .description('설치된 팩 목록')
181
+ .action(packListCommand);
182
+
183
+ pack.command('info <name>')
184
+ .description('팩 상세 정보')
185
+ .action(packInfoCommand);
186
+
187
+ program.parse();
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@stellavault/core",
3
+ "version": "0.1.0",
4
+ "description": "Stellavault core engine — indexer, hybrid search, vector store, MCP server",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "dev": "tsc --watch",
17
+ "test": "vitest run",
18
+ "test:watch": "vitest"
19
+ },
20
+ "devDependencies": {
21
+ "@types/better-sqlite3": "^7.6.13",
22
+ "@types/cors": "^2.8.19",
23
+ "@types/express": "^5.0.6",
24
+ "@types/node": "^25.5.0",
25
+ "typescript": "^5.7.0",
26
+ "vitest": "^3.0.0"
27
+ },
28
+ "dependencies": {
29
+ "@modelcontextprotocol/sdk": "^1.28.0",
30
+ "@xenova/transformers": "^2.17.2",
31
+ "b4a": "^1.8.0",
32
+ "better-sqlite3": "^12.8.0",
33
+ "chokidar": "^5.0.0",
34
+ "cors": "^2.8.6",
35
+ "express": "^5.2.1",
36
+ "gray-matter": "^4.0.3",
37
+ "hyperswarm": "^4.17.0",
38
+ "sqlite-vec": "^0.1.7"
39
+ }
40
+ }
@@ -0,0 +1,138 @@
1
+ // Web Dashboard (P3-F26) — Express에 HTML 대시보드 추가
2
+ // http://localhost:3333/dashboard
3
+
4
+ import type { Express } from 'express';
5
+
6
+ export function mountDashboard(app: Express) {
7
+ app.get('/dashboard', (_req, res) => {
8
+ res.setHeader('Content-Type', 'text/html');
9
+ res.send(getDashboardHTML());
10
+ });
11
+ }
12
+
13
+ function getDashboardHTML(): string {
14
+ return `<!DOCTYPE html>
15
+ <html lang="en">
16
+ <head>
17
+ <meta charset="UTF-8">
18
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
19
+ <title>Stellavault Dashboard</title>
20
+ <style>
21
+ * { margin: 0; padding: 0; box-sizing: border-box; }
22
+ body { font-family: system-ui, -apple-system, sans-serif; background: #050510; color: #c0c0f0; min-height: 100vh; }
23
+ .header { padding: 16px 24px; border-bottom: 1px solid rgba(100,120,255,0.1); display: flex; align-items: center; gap: 12px; }
24
+ .header h1 { font-size: 18px; font-weight: 600; }
25
+ .header .subtitle { color: #556; font-size: 12px; }
26
+ .container { max-width: 1200px; margin: 0 auto; padding: 24px; }
27
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-bottom: 24px; }
28
+ .card { background: rgba(100,120,255,0.04); border: 1px solid rgba(100,120,255,0.1); border-radius: 12px; padding: 16px; }
29
+ .card h3 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #556; margin-bottom: 8px; }
30
+ .card .value { font-size: 28px; font-weight: 700; }
31
+ .card .sub { font-size: 11px; color: #556; margin-top: 4px; }
32
+ .search-box { width: 100%; padding: 10px 16px; background: rgba(100,120,255,0.06); border: 1px solid rgba(100,120,255,0.15); border-radius: 8px; color: #c0c0f0; font-size: 14px; outline: none; margin-bottom: 16px; }
33
+ .search-box::placeholder { color: #445; }
34
+ .results { display: flex; flex-direction: column; gap: 8px; }
35
+ .result { padding: 12px; background: rgba(255,255,255,0.02); border-radius: 8px; cursor: pointer; }
36
+ .result:hover { background: rgba(100,120,255,0.06); }
37
+ .result .title { font-weight: 600; font-size: 13px; }
38
+ .result .meta { font-size: 11px; color: #556; margin-top: 4px; }
39
+ .section { margin-bottom: 24px; }
40
+ .section h2 { font-size: 14px; margin-bottom: 12px; color: #88aaff; }
41
+ .bar { height: 6px; background: rgba(100,120,255,0.1); border-radius: 3px; overflow: hidden; margin-top: 6px; }
42
+ .bar-fill { height: 100%; border-radius: 3px; transition: width 0.3s; }
43
+ .links { display: flex; gap: 12px; margin-top: 16px; }
44
+ .links a { color: #88aaff; text-decoration: none; font-size: 12px; padding: 6px 12px; border: 1px solid rgba(100,120,255,0.15); border-radius: 6px; }
45
+ .links a:hover { background: rgba(100,120,255,0.1); }
46
+ #loading { color: #556; font-size: 12px; }
47
+ </style>
48
+ </head>
49
+ <body>
50
+ <div class="header">
51
+ <h1>Stellavault</h1>
52
+ <span class="subtitle">Dashboard</span>
53
+ <div style="margin-left:auto" class="links">
54
+ <a href="/api/stats" target="_blank">API Stats</a>
55
+ <a href="http://localhost:5173" target="_blank">3D Graph</a>
56
+ </div>
57
+ </div>
58
+
59
+ <div class="container">
60
+ <!-- Stats -->
61
+ <div class="grid" id="stats-grid">
62
+ <div class="card"><h3>Documents</h3><div class="value" id="doc-count">-</div></div>
63
+ <div class="card"><h3>Chunks</h3><div class="value" id="chunk-count">-</div></div>
64
+ <div class="card"><h3>Health Score</h3><div class="value" id="health-score">-</div><div class="bar"><div class="bar-fill" id="health-bar" style="width:0%;background:#10b981"></div></div></div>
65
+ <div class="card"><h3>Knowledge Gaps</h3><div class="value" id="gap-count">-</div></div>
66
+ </div>
67
+
68
+ <!-- Search -->
69
+ <div class="section">
70
+ <h2>Search</h2>
71
+ <input class="search-box" id="search-input" placeholder="Search your knowledge..." />
72
+ <div class="results" id="search-results"></div>
73
+ </div>
74
+
75
+ <!-- Decay -->
76
+ <div class="section">
77
+ <h2>Fading Knowledge</h2>
78
+ <div id="decay-list"><span id="loading">Loading...</span></div>
79
+ </div>
80
+ </div>
81
+
82
+ <script>
83
+ const API = '/api';
84
+ // HIGH-06: XSS 방지 — HTML 이스케이프
85
+ function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
86
+
87
+ async function loadStats() {
88
+ try {
89
+ const [stats, health] = await Promise.all([
90
+ fetch(API + '/stats').then(r => r.json()),
91
+ fetch(API + '/health').then(r => r.json()).catch(() => null),
92
+ ]);
93
+ document.getElementById('doc-count').textContent = stats.documentCount ?? 0;
94
+ document.getElementById('chunk-count').textContent = stats.chunkCount ?? 0;
95
+ if (health) {
96
+ const score = health.decay?.averageR ? Math.round(health.decay.averageR * 100) : 100;
97
+ document.getElementById('health-score').textContent = score + '%';
98
+ document.getElementById('health-bar').style.width = score + '%';
99
+ document.getElementById('health-bar').style.background = score > 70 ? '#10b981' : score > 40 ? '#f59e0b' : '#ef4444';
100
+ document.getElementById('gap-count').textContent = health.gaps?.gapCount ?? 0;
101
+
102
+ // Decay list
103
+ const decayEl = document.getElementById('decay-list');
104
+ if (health.decay?.topDecaying?.length) {
105
+ decayEl.innerHTML = health.decay.topDecaying.slice(0, 8).map(d => {
106
+ const r = Math.round((d.retrievability ?? 0) * 100);
107
+ const color = r > 50 ? '#10b981' : r > 30 ? '#f59e0b' : '#ef4444';
108
+ return '<div class="result"><div class="title">' + esc(d.title) + '</div><div class="bar"><div class="bar-fill" style="width:' + r + '%;background:' + color + '"></div></div><div class="meta">' + r + '% retrievability</div></div>';
109
+ }).join('');
110
+ } else {
111
+ decayEl.innerHTML = '<div style="color:#556;font-size:12px">All knowledge healthy!</div>';
112
+ }
113
+ }
114
+ } catch (e) { console.error(e); }
115
+ }
116
+
117
+ let searchTimer;
118
+ document.getElementById('search-input').addEventListener('input', (e) => {
119
+ clearTimeout(searchTimer);
120
+ searchTimer = setTimeout(async () => {
121
+ const q = e.target.value.trim();
122
+ const el = document.getElementById('search-results');
123
+ if (!q) { el.innerHTML = ''; return; }
124
+ try {
125
+ const res = await fetch(API + '/search?q=' + encodeURIComponent(q) + '&limit=10').then(r => r.json());
126
+ el.innerHTML = (res.results || []).map(r =>
127
+ '<div class="result"><div class="title">' + esc(r.title) + ' <span style="color:#556;font-size:11px">(' + Math.round(r.score * 100) + '%)</span></div>' +
128
+ '<div class="meta">' + esc((r.highlights?.[0] || '').slice(0, 100)) + '</div></div>'
129
+ ).join('') || '<div style="color:#556;font-size:12px">No results</div>';
130
+ } catch { el.innerHTML = '<div style="color:#ef4444;font-size:12px">Search error</div>'; }
131
+ }, 300);
132
+ });
133
+
134
+ loadStats();
135
+ </script>
136
+ </body>
137
+ </html>`;
138
+ }
@@ -0,0 +1,286 @@
1
+ // Design Ref: §4.2 — Graph Data 생성 알고리즘
2
+ // Design Ref: §6.2 — K-Means 클러스터링
3
+
4
+ import type { VectorStore } from '../store/types.js';
5
+ import type { GraphNode, GraphEdge, Cluster, GraphData } from '../types/graph.js';
6
+ import { createHash } from 'node:crypto';
7
+
8
+ const CLUSTER_COLORS = [
9
+ '#6366f1', '#ec4899', '#f59e0b', '#10b981', '#3b82f6',
10
+ '#8b5cf6', '#ef4444', '#14b8a6', '#f97316', '#06b6d4',
11
+ '#84cc16', '#e879f9', '#22d3ee', '#a3e635', '#fb923c',
12
+ ];
13
+
14
+ export type GraphMode = 'semantic' | 'folder';
15
+
16
+ export interface BuildGraphOptions {
17
+ mode?: GraphMode; // default: 'semantic'
18
+ edgeThreshold?: number; // default: 0.15
19
+ maxEdgesPerNode?: number; // default: 5
20
+ clusterCount?: number; // 0 = auto (Elbow)
21
+ }
22
+
23
+ export async function buildGraphData(
24
+ store: VectorStore,
25
+ options: BuildGraphOptions = {},
26
+ ): Promise<GraphData> {
27
+ const {
28
+ edgeThreshold = 0.15,
29
+ maxEdgesPerNode = 5,
30
+ } = options;
31
+
32
+ // 1. 모든 문서 + 임베딩 로드
33
+ const [docs, embeddings] = await Promise.all([
34
+ store.getAllDocuments(),
35
+ store.getDocumentEmbeddings(),
36
+ ]);
37
+
38
+ // 2. k-NN으로 엣지 생성
39
+ const edges: GraphEdge[] = [];
40
+ const edgeCounts = new Map<string, number>();
41
+
42
+ for (const doc of docs) {
43
+ const vec = embeddings.get(doc.id);
44
+ if (!vec) continue;
45
+
46
+ // 모든 다른 문서와 코사인 유사도 계산
47
+ const similarities: Array<{ id: string; sim: number }> = [];
48
+ for (const other of docs) {
49
+ if (other.id === doc.id) continue;
50
+ const otherVec = embeddings.get(other.id);
51
+ if (!otherVec) continue;
52
+ const sim = cosineSimilarity(vec, otherVec);
53
+ if (sim >= edgeThreshold) {
54
+ similarities.push({ id: other.id, sim });
55
+ }
56
+ }
57
+
58
+ // 상위 k개만
59
+ similarities.sort((a, b) => b.sim - a.sim);
60
+ const topK = similarities.slice(0, maxEdgesPerNode);
61
+
62
+ for (const { id: targetId, sim } of topK) {
63
+ // 중복 엣지 방지 (A→B, B→A)
64
+ const edgeKey = [doc.id, targetId].sort().join(':');
65
+ if (!edgeCounts.has(edgeKey)) {
66
+ edges.push({ source: doc.id, target: targetId, weight: sim });
67
+ edgeCounts.set(edgeKey, 1);
68
+ }
69
+ }
70
+ }
71
+
72
+ // 3. 클러스터링 — 모드에 따라 분기
73
+ const mode = options.mode ?? 'semantic';
74
+ let assignmentMap: Map<string, number>;
75
+ let clusters: Cluster[];
76
+
77
+ if (mode === 'folder') {
78
+ // 폴더 기반: 최상위 폴더를 클러스터로 사용
79
+ const folderMap = new Map<string, number>();
80
+ const folderNames: string[] = [];
81
+
82
+ for (const doc of docs) {
83
+ const topFolder = doc.filePath.split('/')[0] ?? 'root';
84
+ if (!folderMap.has(topFolder)) {
85
+ folderMap.set(topFolder, folderNames.length);
86
+ folderNames.push(topFolder);
87
+ }
88
+ }
89
+
90
+ assignmentMap = new Map<string, number>();
91
+ for (const doc of docs) {
92
+ const topFolder = doc.filePath.split('/')[0] ?? 'root';
93
+ assignmentMap.set(doc.id, folderMap.get(topFolder)!);
94
+ }
95
+
96
+ // 폴더별 클러스터
97
+ const folderCounts = new Map<number, number>();
98
+ for (const [, cId] of assignmentMap) {
99
+ folderCounts.set(cId, (folderCounts.get(cId) ?? 0) + 1);
100
+ }
101
+
102
+ clusters = folderNames.map((name, i) => ({
103
+ id: i,
104
+ label: name.replace(/^\d+_/, ''), // "04_Projects" → "Projects"
105
+ color: CLUSTER_COLORS[i % CLUSTER_COLORS.length],
106
+ nodeCount: folderCounts.get(i) ?? 0,
107
+ }));
108
+ } else {
109
+ // 시맨틱 기반: K-means
110
+ const docIds = docs.filter(d => embeddings.has(d.id)).map(d => d.id);
111
+ const vectors = docIds.map(id => embeddings.get(id)!);
112
+ const k = Math.min(Math.max(5, Math.round(Math.sqrt(docIds.length / 5))), 10);
113
+ const assignments = kMeans(vectors, k);
114
+
115
+ // 클러스터별 문서 수집 (id + title)
116
+ const clusterDocInfos = new Map<number, Array<{ id: string; title: string }>>();
117
+ for (let i = 0; i < docIds.length; i++) {
118
+ const cId = assignments[i];
119
+ if (!clusterDocInfos.has(cId)) clusterDocInfos.set(cId, []);
120
+ const doc = docs.find(d => d.id === docIds[i]);
121
+ if (doc) clusterDocInfos.get(cId)!.push({ id: doc.id, title: doc.title });
122
+ }
123
+
124
+ // 엣지 기반 연결 수 계산 (대표 노드 선정용)
125
+ const connCounts = new Map<string, number>();
126
+ for (const e of edges) {
127
+ connCounts.set(e.source, (connCounts.get(e.source) ?? 0) + 1);
128
+ connCounts.set(e.target, (connCounts.get(e.target) ?? 0) + 1);
129
+ }
130
+
131
+ clusters = [];
132
+ for (const [cId, docInfos] of clusterDocInfos) {
133
+ // 가장 연결이 많은 노드 = 대표 노드
134
+ const sorted = [...docInfos].sort((a, b) =>
135
+ (connCounts.get(b.id) ?? 0) - (connCounts.get(a.id) ?? 0)
136
+ );
137
+ const representative = sorted[0]?.title ?? 'Cluster';
138
+ clusters.push({
139
+ id: cId,
140
+ label: `${representative} (${docInfos.length})`,
141
+ color: CLUSTER_COLORS[cId % CLUSTER_COLORS.length],
142
+ nodeCount: docInfos.length,
143
+ });
144
+ }
145
+
146
+ assignmentMap = new Map<string, number>();
147
+ for (let i = 0; i < docIds.length; i++) {
148
+ assignmentMap.set(docIds[i], assignments[i]);
149
+ }
150
+ }
151
+
152
+ // 4. 노드 생성
153
+
154
+ const connectionCounts = new Map<string, number>();
155
+ for (const edge of edges) {
156
+ connectionCounts.set(edge.source, (connectionCounts.get(edge.source) ?? 0) + 1);
157
+ connectionCounts.set(edge.target, (connectionCounts.get(edge.target) ?? 0) + 1);
158
+ }
159
+ const maxConnections = Math.max(1, ...connectionCounts.values());
160
+
161
+ const nodes: GraphNode[] = docs.map(doc => {
162
+ const conns = connectionCounts.get(doc.id) ?? 0;
163
+ const ratio = conns / maxConnections; // 0~1
164
+ // 지수 스케일: 상위 노드만 극적으로 커짐 (ratio^0.5 → 중심부 강조)
165
+ const size = 1 + 6 * Math.pow(ratio, 0.5);
166
+ return {
167
+ id: doc.id,
168
+ label: doc.title.slice(0, 40),
169
+ filePath: doc.filePath,
170
+ tags: doc.tags,
171
+ clusterId: assignmentMap.get(doc.id) ?? 0,
172
+ size,
173
+ source: doc.source ?? 'local',
174
+ type: doc.type ?? 'note',
175
+ lastModified: doc.lastModified,
176
+ };
177
+ });
178
+
179
+ // 5. cache key
180
+ const cacheKey = createHash('md5')
181
+ .update(JSON.stringify({ nodeCount: nodes.length, edgeCount: edges.length }))
182
+ .digest('hex')
183
+ .slice(0, 8);
184
+
185
+ return {
186
+ nodes,
187
+ edges,
188
+ clusters,
189
+ stats: {
190
+ nodeCount: nodes.length,
191
+ edgeCount: edges.length,
192
+ clusterCount: clusters.length,
193
+ },
194
+ };
195
+ }
196
+
197
+ // --- 유틸리티 ---
198
+
199
+ function cosineSimilarity(a: number[], b: number[]): number {
200
+ let dot = 0, normA = 0, normB = 0;
201
+ for (let i = 0; i < a.length; i++) {
202
+ dot += a[i] * b[i];
203
+ normA += a[i] * a[i];
204
+ normB += b[i] * b[i];
205
+ }
206
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
207
+ return denom === 0 ? 0 : dot / denom;
208
+ }
209
+
210
+ function kMeans(vectors: number[][], k: number, maxIter: number = 50): number[] {
211
+ if (vectors.length === 0) return [];
212
+ const dims = vectors[0].length;
213
+
214
+ // K-means++ 초기화
215
+ const centroids: number[][] = [vectors[Math.floor(Math.random() * vectors.length)].slice()];
216
+ for (let c = 1; c < k; c++) {
217
+ const dists = vectors.map(v => {
218
+ let minD = Infinity;
219
+ for (const cent of centroids) {
220
+ const d = euclideanDist(v, cent);
221
+ if (d < minD) minD = d;
222
+ }
223
+ return minD;
224
+ });
225
+ const totalDist = dists.reduce((a, b) => a + b, 0);
226
+ let r = Math.random() * totalDist;
227
+ for (let i = 0; i < dists.length; i++) {
228
+ r -= dists[i];
229
+ if (r <= 0) { centroids.push(vectors[i].slice()); break; }
230
+ }
231
+ if (centroids.length <= c) centroids.push(vectors[Math.floor(Math.random() * vectors.length)].slice());
232
+ }
233
+
234
+ const assignments = new Array<number>(vectors.length).fill(0);
235
+
236
+ for (let iter = 0; iter < maxIter; iter++) {
237
+ let changed = false;
238
+
239
+ // Assign
240
+ for (let i = 0; i < vectors.length; i++) {
241
+ let bestC = 0, bestD = Infinity;
242
+ for (let c = 0; c < k; c++) {
243
+ const d = euclideanDist(vectors[i], centroids[c]);
244
+ if (d < bestD) { bestD = d; bestC = c; }
245
+ }
246
+ if (assignments[i] !== bestC) { assignments[i] = bestC; changed = true; }
247
+ }
248
+
249
+ if (!changed) break;
250
+
251
+ // Update centroids
252
+ for (let c = 0; c < k; c++) {
253
+ const members = vectors.filter((_, i) => assignments[i] === c);
254
+ if (members.length === 0) continue;
255
+ for (let d = 0; d < dims; d++) {
256
+ centroids[c][d] = members.reduce((sum, v) => sum + v[d], 0) / members.length;
257
+ }
258
+ }
259
+ }
260
+
261
+ return assignments;
262
+ }
263
+
264
+ function euclideanDist(a: number[], b: number[]): number {
265
+ let sum = 0;
266
+ for (let i = 0; i < a.length; i++) {
267
+ const diff = a[i] - b[i];
268
+ sum += diff * diff;
269
+ }
270
+ return Math.sqrt(sum);
271
+ }
272
+
273
+ function extractClusterLabel(titles: string[]): string {
274
+ // 제목에서 빈출 단어 추출 (2글자 이상)
275
+ const wordCounts = new Map<string, number>();
276
+ const stopWords = new Set(['the', 'a', 'an', 'in', 'on', 'at', 'to', 'for', 'of', 'and', 'or', 'is', 'are', 'was', 'be']);
277
+ for (const title of titles) {
278
+ const words = title.replace(/[^\w가-힣\s]/g, '').split(/\s+/).filter(w => w.length >= 2 && !stopWords.has(w.toLowerCase()));
279
+ const seen = new Set<string>();
280
+ for (const w of words) {
281
+ if (!seen.has(w)) { wordCounts.set(w, (wordCounts.get(w) ?? 0) + 1); seen.add(w); }
282
+ }
283
+ }
284
+ const sorted = [...wordCounts.entries()].sort((a, b) => b[1] - a[1]);
285
+ return sorted.slice(0, 3).map(([w]) => w).join(', ') || `Cluster`;
286
+ }