@chigichan24/crune 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 (40) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +155 -0
  3. package/bin/crune.js +2 -0
  4. package/dist-cli/__tests__/cli.test.js +63 -0
  5. package/dist-cli/__tests__/clustering.test.js +200 -0
  6. package/dist-cli/__tests__/community.test.js +115 -0
  7. package/dist-cli/__tests__/edges.test.js +130 -0
  8. package/dist-cli/__tests__/feature-extraction.test.js +66 -0
  9. package/dist-cli/__tests__/fixtures.js +192 -0
  10. package/dist-cli/__tests__/orchestrator.test.js +253 -0
  11. package/dist-cli/__tests__/session-parser.test.js +335 -0
  12. package/dist-cli/__tests__/session-summarizer.test.js +117 -0
  13. package/dist-cli/__tests__/skill-server.test.js +191 -0
  14. package/dist-cli/__tests__/svd.test.js +112 -0
  15. package/dist-cli/__tests__/tfidf.test.js +88 -0
  16. package/dist-cli/__tests__/tokenizer.test.js +125 -0
  17. package/dist-cli/__tests__/topic-nodes.test.js +184 -0
  18. package/dist-cli/analyze-sessions.js +476 -0
  19. package/dist-cli/cli.js +215 -0
  20. package/dist-cli/knowledge-graph/clustering.js +174 -0
  21. package/dist-cli/knowledge-graph/community.js +220 -0
  22. package/dist-cli/knowledge-graph/constants.js +58 -0
  23. package/dist-cli/knowledge-graph/edges.js +193 -0
  24. package/dist-cli/knowledge-graph/feature-extraction.js +124 -0
  25. package/dist-cli/knowledge-graph/index.js +235 -0
  26. package/dist-cli/knowledge-graph/reusability.js +51 -0
  27. package/dist-cli/knowledge-graph/similarity.js +13 -0
  28. package/dist-cli/knowledge-graph/skill-generator.js +203 -0
  29. package/dist-cli/knowledge-graph/svd.js +195 -0
  30. package/dist-cli/knowledge-graph/tfidf.js +54 -0
  31. package/dist-cli/knowledge-graph/tokenizer.js +66 -0
  32. package/dist-cli/knowledge-graph/tool-pattern.js +173 -0
  33. package/dist-cli/knowledge-graph/topic-nodes.js +199 -0
  34. package/dist-cli/knowledge-graph/types.js +4 -0
  35. package/dist-cli/knowledge-graph-builder.js +27 -0
  36. package/dist-cli/session-parser.js +360 -0
  37. package/dist-cli/session-summarizer.js +133 -0
  38. package/dist-cli/skill-server.js +62 -0
  39. package/dist-cli/skill-synthesizer.js +189 -0
  40. package/package.json +47 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Kazuki CHIGITA]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ <div align="center">
2
+ <img src="public/favicon.svg" alt="crune logo" width="80" height="80" />
3
+ <h1>crune</h1>
4
+ <p><strong>Claude Code Rune — Traces linger, skills emerge</strong></p>
5
+ </div>
6
+
7
+ Decipher the traces etched in past sessions and resurrect them as reusable skills. crune is a static web dashboard that analyzes Claude Code session logs, providing session playback, analytics, a semantic knowledge graph, and skill synthesis.
8
+
9
+ ## Features
10
+
11
+ - **Session Playback** --- Turn-by-turn conversation replay with minimap navigation, tool call inspection, and subagent branch expansion
12
+ - **Overview Dashboard** --- Activity heatmap, project distribution, tool usage trends, duration distribution, model usage, and top edited files
13
+ - **Semantic Knowledge Graph** --- TF-IDF + Tool-IDF + structural features, Truncated SVD, agglomerative clustering, Louvain community detection, Brandes centrality ([algorithm details](docs/knowledge-graph-algorithm.md))
14
+ - **Tacit Knowledge** --- Extracted workflow patterns, tool sequences, and pain points (long sessions, hot files)
15
+ - **Session Summarization** --- Automatic session summary and classification (no LLM required)
16
+ - **Skill Synthesis** --- Synthesize reusable skill definitions from the knowledge graph ([algorithm details](docs/skill-generation-algorithm.md))
17
+
18
+ ### Overview Dashboard
19
+
20
+ <img src="docs/overview.png" alt="Overview Dashboard" width="800" />
21
+
22
+ ### Session Playback
23
+
24
+ <img src="docs/playback.png" alt="Session Playback" width="800" />
25
+
26
+ ### Semantic Knowledge Graph (Rune)
27
+
28
+ <img src="docs/rune.png" alt="Knowledge Graph" width="800" />
29
+
30
+ ## Quick Start
31
+
32
+ ```bash
33
+ npm install
34
+
35
+ # Analyze Claude Code session logs (~/.claude/projects/)
36
+ npm run analyze-sessions
37
+
38
+ # Start dev server
39
+ npm run dev
40
+ ```
41
+
42
+ ## Data Pipeline
43
+
44
+ `npm run analyze-sessions` reads JSONL session files from `~/.claude/projects/` and outputs structured JSON to `public/data/sessions/`.
45
+
46
+ ```
47
+ ~/.claude/projects/**/*.jsonl
48
+ -> parse & build turns
49
+ -> extract metadata, subagents, linked plans
50
+ -> session summarization (centrality-based representative prompt, workType classification)
51
+ -> TF-IDF + Tool-IDF + structural features -> Truncated SVD -> agglomerative clustering -> Louvain
52
+ -> skill synthesis (reusability score top-N -> claude -p)
53
+ -> output:
54
+ public/data/sessions/index.json (session list)
55
+ public/data/sessions/overview.json (cross-session analytics + knowledge graph)
56
+ public/data/sessions/detail/*.json (individual session playback data)
57
+ ```
58
+
59
+ Custom paths:
60
+
61
+ ```bash
62
+ npm run analyze-sessions -- --sessions-dir /path/to/sessions --output-dir /path/to/output
63
+ ```
64
+
65
+ ## Session Summarization
66
+
67
+ The session list displays auto-generated summaries, processed entirely locally without LLM.
68
+
69
+ - **Representative prompt selection**: Selects the most representative prompt from plan mode turns using Jaccard centrality with position weighting
70
+ - **workType classification**: Automatically classifies each session into one of four types:
71
+ - `investigation` --- Exploratory, read-heavy sessions
72
+ - `implementation` --- Edit/write-heavy coding sessions
73
+ - `debugging` --- Bash-heavy sessions with edits
74
+ - `planning` --- Plan mode sessions with few tool calls
75
+ - **Keyword extraction**: Extracts top keywords from session prompts
76
+ - **Scope estimation**: Infers the session scope from the common directory prefix of edited files
77
+
78
+ ## Skill Synthesis
79
+
80
+ Synthesizes reusable skill definitions from knowledge graph analysis. Follows the [anthropics/skills](https://github.com/anthropics/skills) format.
81
+
82
+ - **Pre-synthesis**: Automatically synthesizes the top 5 skill candidates via `claude -p` during `analyze-sessions`
83
+ - **Instant display**: Synthesized skills are immediately viewable and copyable in the UI
84
+ - **On-demand re-synthesis**: The re-synthesis button generates a full version enriched with graph context (connected topics, community, centrality)
85
+ - **Local server**: `npm run skill-server` starts the synthesis API server (localhost:3456)
86
+
87
+ Synthesis options:
88
+
89
+ ```bash
90
+ # Specify model (e.g. haiku for speed)
91
+ npm run analyze-sessions -- --synthesis-model haiku
92
+
93
+ # Change number of candidates to synthesize (default: 5)
94
+ npm run analyze-sessions -- --synthesis-count 10
95
+
96
+ # Skip LLM synthesis (graph construction only)
97
+ npm run analyze-sessions -- --skip-synthesis
98
+ ```
99
+
100
+ ## Scripts
101
+
102
+ | Command | Description |
103
+ |---------|-------------|
104
+ | `npm run dev` | Start Vite dev server |
105
+ | `npm run build` | Type-check + production build |
106
+ | `npm run preview` | Preview production build |
107
+ | `npm run lint` | Run ESLint |
108
+ | `npm run analyze-sessions` | Run data pipeline |
109
+ | `npm run skill-server` | Skill synthesis local server (localhost:3456) |
110
+ | `npm run dev:full` | skill-server + Vite dev server together |
111
+
112
+ ### Synthesis options for analyze-sessions
113
+
114
+ | Flag | Description |
115
+ |------|-------------|
116
+ | `--synthesis-model <model>` | Model to use for synthesis (e.g. `haiku` for speed) |
117
+ | `--synthesis-count <n>` | Number of candidates to synthesize (default: 5) |
118
+ | `--skip-synthesis` | Skip LLM synthesis |
119
+
120
+ ## Tech Stack
121
+
122
+ - React 19 + TypeScript 5.9
123
+ - Vite 8
124
+ - Chart.js + react-chartjs-2
125
+ - react-force-graph-2d (d3-force)
126
+ - Plain CSS (no CSS-in-JS, no Tailwind)
127
+
128
+ ## Project Structure
129
+
130
+ ```
131
+ src/
132
+ components/
133
+ overview/ # Dashboard cards, session list, charts
134
+ playback/ # Session replay, tool call blocks, subagent branches
135
+ knowledge/ # Force graph, node detail, tacit knowledge, skill synthesis
136
+ hooks/ # Data fetching (useSessionIndex, useSessionDetail, useSessionOverview)
137
+ types/ # TypeScript type definitions
138
+ scripts/
139
+ analyze-sessions.ts # JSONL -> JSON pipeline
140
+ session-summarizer.ts # Session summarization (local NLP)
141
+ skill-synthesizer.ts # Skill synthesis (claude -p)
142
+ skill-server.ts # Synthesis HTTP server
143
+ knowledge-graph-builder.ts # Semantic embedding + graph construction
144
+ public/
145
+ data/sessions/ # Generated JSON (gitignored)
146
+ ```
147
+
148
+ ## Prerequisites
149
+
150
+ - Node.js >= 18
151
+ - Claude Code session logs at `~/.claude/projects/`
152
+
153
+ ## License
154
+
155
+ Apache-2.0 license
package/bin/crune.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist-cli/cli.js";
@@ -0,0 +1,63 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { parseCliArgs } from "../cli.js";
3
+ describe("parseCliArgs", () => {
4
+ it("returns defaults when no args given", () => {
5
+ const result = parseCliArgs(["node", "cli.ts"]);
6
+ expect(result.sessionsDir).toMatch(/\.claude\/projects$/);
7
+ expect(result.outputDir).toMatch(/skills$/);
8
+ expect(result.count).toBe(5);
9
+ expect(result.model).toBeUndefined();
10
+ expect(result.skipSynthesis).toBe(false);
11
+ expect(result.dryRun).toBe(false);
12
+ });
13
+ it("sets sessionsDir with --sessions-dir", () => {
14
+ const result = parseCliArgs(["node", "cli.ts", "--sessions-dir", "/tmp/sessions"]);
15
+ expect(result.sessionsDir).toBe("/tmp/sessions");
16
+ });
17
+ it("sets outputDir with --output-dir", () => {
18
+ const result = parseCliArgs(["node", "cli.ts", "--output-dir", "/tmp/out"]);
19
+ expect(result.outputDir).toBe("/tmp/out");
20
+ });
21
+ it("sets count with --count", () => {
22
+ const result = parseCliArgs(["node", "cli.ts", "--count", "3"]);
23
+ expect(result.count).toBe(3);
24
+ });
25
+ it("clamps count to minimum of 1", () => {
26
+ const result = parseCliArgs(["node", "cli.ts", "--count", "0"]);
27
+ expect(result.count).toBe(1);
28
+ });
29
+ it("sets model with --model", () => {
30
+ const result = parseCliArgs(["node", "cli.ts", "--model", "haiku"]);
31
+ expect(result.model).toBe("haiku");
32
+ });
33
+ it("sets skipSynthesis with --skip-synthesis", () => {
34
+ const result = parseCliArgs(["node", "cli.ts", "--skip-synthesis"]);
35
+ expect(result.skipSynthesis).toBe(true);
36
+ });
37
+ it("sets dryRun with --dry-run", () => {
38
+ const result = parseCliArgs(["node", "cli.ts", "--dry-run"]);
39
+ expect(result.dryRun).toBe(true);
40
+ });
41
+ it("handles multiple flags combined", () => {
42
+ const result = parseCliArgs([
43
+ "node",
44
+ "cli.ts",
45
+ "--sessions-dir",
46
+ "/tmp/sessions",
47
+ "--output-dir",
48
+ "/tmp/out",
49
+ "--count",
50
+ "10",
51
+ "--model",
52
+ "sonnet",
53
+ "--skip-synthesis",
54
+ "--dry-run",
55
+ ]);
56
+ expect(result.sessionsDir).toBe("/tmp/sessions");
57
+ expect(result.outputDir).toBe("/tmp/out");
58
+ expect(result.count).toBe(10);
59
+ expect(result.model).toBe("sonnet");
60
+ expect(result.skipSynthesis).toBe(true);
61
+ expect(result.dryRun).toBe(true);
62
+ });
63
+ });
@@ -0,0 +1,200 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { cosineSimilarity, cosineDistance, agglomerativeClusteringFromDistMatrix, findElbowThreshold, clusterWithThresholdFromDistMatrix, splitOversizedClusters, } from "../knowledge-graph-builder.js";
3
+ // Helper: create an L2-normalized Float64Array from raw values
4
+ function normalized(...values) {
5
+ const norm = Math.sqrt(values.reduce((s, v) => s + v * v, 0));
6
+ return new Float64Array(values.map((v) => v / norm));
7
+ }
8
+ // Helper: build a distance map with key format `${min}:${max}`
9
+ function buildDistMap(entries) {
10
+ const m = new Map();
11
+ for (const [i, j, d] of entries) {
12
+ const lo = Math.min(i, j);
13
+ const hi = Math.max(i, j);
14
+ m.set(`${lo}:${hi}`, d);
15
+ }
16
+ return m;
17
+ }
18
+ // ─── cosineSimilarity ───────────────────────────────────────────────────────
19
+ describe("cosineSimilarity", () => {
20
+ it("returns ~1.0 for identical normalized vectors", () => {
21
+ const v = normalized(1, 2, 3);
22
+ expect(cosineSimilarity(v, v)).toBeCloseTo(1.0, 10);
23
+ });
24
+ it("returns ~0.0 for orthogonal normalized vectors", () => {
25
+ const a = normalized(1, 0, 0);
26
+ const b = normalized(0, 1, 0);
27
+ expect(cosineSimilarity(a, b)).toBeCloseTo(0.0, 10);
28
+ });
29
+ });
30
+ // ─── cosineDistance ──────────────────────────────────────────────────────────
31
+ describe("cosineDistance", () => {
32
+ it("equals 1 - cosineSimilarity", () => {
33
+ const a = normalized(1, 2, 3);
34
+ const b = normalized(3, 2, 1);
35
+ const sim = cosineSimilarity(a, b);
36
+ const dist = cosineDistance(a, b);
37
+ expect(dist).toBeCloseTo(1 - sim, 10);
38
+ });
39
+ it("returns ~0.0 for identical vectors", () => {
40
+ const v = normalized(4, 5, 6);
41
+ expect(cosineDistance(v, v)).toBeCloseTo(0.0, 10);
42
+ });
43
+ it("returns ~1.0 for orthogonal vectors", () => {
44
+ const a = normalized(1, 0);
45
+ const b = normalized(0, 1);
46
+ expect(cosineDistance(a, b)).toBeCloseTo(1.0, 10);
47
+ });
48
+ });
49
+ // ─── agglomerativeClusteringFromDistMatrix ──────────────────────────────────
50
+ describe("agglomerativeClusteringFromDistMatrix", () => {
51
+ it("returns [] for 0 sessions", () => {
52
+ const result = agglomerativeClusteringFromDistMatrix([], new Map());
53
+ expect(result).toEqual([]);
54
+ });
55
+ it("returns [[0]] for 1 session", () => {
56
+ const result = agglomerativeClusteringFromDistMatrix(["s0"], new Map());
57
+ expect(result).toEqual([[0]]);
58
+ });
59
+ it("groups 2 close sessions apart from 1 distant session", () => {
60
+ // Sessions 0 and 1 are very close (dist 0.05), session 2 is far from both
61
+ const dist = buildDistMap([
62
+ [0, 1, 0.05],
63
+ [0, 2, 0.95],
64
+ [1, 2, 0.95],
65
+ ]);
66
+ const clusters = agglomerativeClusteringFromDistMatrix(["s0", "s1", "s2"], dist);
67
+ // Should produce 2 clusters: one with {0,1} and one with {2}
68
+ expect(clusters.length).toBe(2);
69
+ const sorted = clusters
70
+ .map((c) => [...c].sort((a, b) => a - b))
71
+ .sort((a, b) => a[0] - b[0]);
72
+ expect(sorted).toEqual([[0, 1], [2]]);
73
+ });
74
+ });
75
+ // ─── findElbowThreshold ─────────────────────────────────────────────────────
76
+ describe("findElbowThreshold", () => {
77
+ it("returns 0.7 for fewer than 3 distances", () => {
78
+ expect(findElbowThreshold([])).toBe(0.7);
79
+ expect(findElbowThreshold([0.5])).toBe(0.7);
80
+ expect(findElbowThreshold([0.3, 0.6])).toBe(0.7);
81
+ });
82
+ it("detects a jump and returns a value in [0.3, 0.9]", () => {
83
+ const distances = [0.1, 0.2, 0.8, 0.9];
84
+ const threshold = findElbowThreshold(distances);
85
+ expect(threshold).toBeGreaterThanOrEqual(0.3);
86
+ expect(threshold).toBeLessThanOrEqual(0.9);
87
+ });
88
+ it("clamps to 0.3 when all distances are very small", () => {
89
+ const distances = [0.01, 0.02, 0.03, 0.04, 0.05];
90
+ const threshold = findElbowThreshold(distances);
91
+ expect(threshold).toBe(0.3);
92
+ });
93
+ it("clamps to 0.9 when all distances are very large", () => {
94
+ const distances = [0.91, 0.95, 0.99, 1.0, 1.2];
95
+ const threshold = findElbowThreshold(distances);
96
+ expect(threshold).toBe(0.9);
97
+ });
98
+ });
99
+ // ─── clusterWithThresholdFromDistMatrix ─────────────────────────────────────
100
+ describe("clusterWithThresholdFromDistMatrix", () => {
101
+ it("returns [] for n=0", () => {
102
+ expect(clusterWithThresholdFromDistMatrix(0, new Map(), 0.5)).toEqual([]);
103
+ });
104
+ it("returns [[0]] for n=1", () => {
105
+ expect(clusterWithThresholdFromDistMatrix(1, new Map(), 0.5)).toEqual([[0]]);
106
+ });
107
+ it("merges pairs below threshold", () => {
108
+ // 0-1 close, 2 far
109
+ const dist = buildDistMap([
110
+ [0, 1, 0.1],
111
+ [0, 2, 0.8],
112
+ [1, 2, 0.8],
113
+ ]);
114
+ const clusters = clusterWithThresholdFromDistMatrix(3, dist, 0.5);
115
+ expect(clusters.length).toBe(2);
116
+ const flat = clusters.map((c) => [...c].sort()).sort((a, b) => a[0] - b[0]);
117
+ expect(flat).toEqual([[0, 1], [2]]);
118
+ });
119
+ it("keeps all singletons when threshold is very low", () => {
120
+ const dist = buildDistMap([
121
+ [0, 1, 0.5],
122
+ [0, 2, 0.6],
123
+ [1, 2, 0.7],
124
+ ]);
125
+ const clusters = clusterWithThresholdFromDistMatrix(3, dist, 0.01);
126
+ expect(clusters.length).toBe(3);
127
+ });
128
+ it("merges everything when threshold is very high", () => {
129
+ const dist = buildDistMap([
130
+ [0, 1, 0.3],
131
+ [0, 2, 0.4],
132
+ [1, 2, 0.5],
133
+ ]);
134
+ const clusters = clusterWithThresholdFromDistMatrix(3, dist, 2.0);
135
+ expect(clusters.length).toBe(1);
136
+ expect([...clusters[0]].sort()).toEqual([0, 1, 2]);
137
+ });
138
+ });
139
+ // ─── splitOversizedClusters ─────────────────────────────────────────────────
140
+ describe("splitOversizedClusters", () => {
141
+ it("passes through clusters that are under maxSize", () => {
142
+ const clusters = [[0, 1], [2, 3]];
143
+ const dist = buildDistMap([
144
+ [0, 1, 0.2],
145
+ [2, 3, 0.3],
146
+ [0, 2, 0.8],
147
+ [0, 3, 0.8],
148
+ [1, 2, 0.8],
149
+ [1, 3, 0.8],
150
+ ]);
151
+ const result = splitOversizedClusters(clusters, 100, dist);
152
+ // maxSize = max(10, floor(100 * 0.25)) = 25, both clusters are size 2
153
+ expect(result).toEqual([[0, 1], [2, 3]]);
154
+ });
155
+ it("splits an oversized cluster", () => {
156
+ // Create a cluster of 12 members with totalSessions=20, ratio=0.25
157
+ // maxSize = max(10, floor(20 * 0.25)) = 10, so cluster of 12 is oversized
158
+ const bigCluster = Array.from({ length: 12 }, (_, i) => i);
159
+ const smallCluster = [12, 13];
160
+ // Build distances: two groups within the big cluster
161
+ // Group A (0-5): close to each other, far from group B
162
+ // Group B (6-11): close to each other, far from group A
163
+ const dist = new Map();
164
+ for (let i = 0; i < 14; i++) {
165
+ for (let j = i + 1; j < 14; j++) {
166
+ const groupI = i < 6 ? "A" : i < 12 ? "B" : "S";
167
+ const groupJ = j < 6 ? "A" : j < 12 ? "B" : "S";
168
+ let d;
169
+ if (groupI === groupJ) {
170
+ d = 0.1; // same group: close
171
+ }
172
+ else {
173
+ d = 0.9; // different group: far
174
+ }
175
+ dist.set(`${i}:${j}`, d);
176
+ }
177
+ }
178
+ const result = splitOversizedClusters([bigCluster, smallCluster], 20, dist);
179
+ // The small cluster should pass through
180
+ // The big cluster should be split into at least 2 sub-clusters
181
+ expect(result.length).toBeGreaterThanOrEqual(3); // at least 2 from split + 1 small
182
+ // All original indices should be present
183
+ const allIndices = result.flat().sort((a, b) => a - b);
184
+ expect(allIndices).toEqual(Array.from({ length: 14 }, (_, i) => i));
185
+ });
186
+ it("respects custom maxClusterRatio", () => {
187
+ // 5 members, totalSessions=10, ratio=0.3 -> maxSize = max(10, floor(10*0.3)) = 10
188
+ // So cluster of 5 is fine with ratio 0.3
189
+ const clusters = [[0, 1, 2, 3, 4]];
190
+ const dist = new Map();
191
+ for (let i = 0; i < 5; i++) {
192
+ for (let j = i + 1; j < 5; j++) {
193
+ dist.set(`${i}:${j}`, 0.2);
194
+ }
195
+ }
196
+ const result = splitOversizedClusters(clusters, 10, dist, 0.3);
197
+ // maxSize = max(10, 3) = 10, cluster size 5 <= 10, so no split
198
+ expect(result).toEqual([[0, 1, 2, 3, 4]]);
199
+ });
200
+ });