claude-roi 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Akshat Sahu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -151,36 +151,7 @@ Codelens-AI/
151
151
 
152
152
  ## Contributing
153
153
 
154
- Contributions welcome! Here's how to get started:
155
-
156
- ```bash
157
- # 1. Fork the repo on GitHub
158
-
159
- # 2. Clone your fork
160
- git clone https://github.com/YOUR_USERNAME/Codelens-AI.git
161
- cd Codelens-AI
162
-
163
- # 3. Install dependencies
164
- npm install
165
-
166
- # 4. Run in dev mode (no auto-open browser)
167
- node src/index.js --no-open
168
-
169
- # 5. Make your changes and test
170
- node src/index.js --json | head -30 # verify JSON output
171
- node src/index.js --no-open # test dashboard at localhost:3457
172
-
173
- # 6. Submit a pull request
174
- ```
175
-
176
- ### Ideas for contributions
177
-
178
- - Support for other AI coding tools (Copilot, Cursor, etc.)
179
- - Git blame-based line survival tracking (more accurate than the 24h heuristic)
180
- - Export dashboard as PDF/PNG
181
- - Historical trend tracking across multiple runs
182
- - Team/multi-user support
183
- - Custom pricing configuration via CLI flag or config file
154
+ Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, guidelines, and ideas for contributions.
184
155
 
185
156
  ## Privacy
186
157
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-roi",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Correlate Claude Code token usage with git output to measure AI coding agent ROI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -9,7 +9,8 @@
9
9
  "main": "./src/index.js",
10
10
  "scripts": {
11
11
  "start": "node src/index.js",
12
- "dev": "node src/index.js --no-open"
12
+ "dev": "node src/index.js --no-open",
13
+ "test": "npx playwright test"
13
14
  },
14
15
  "keywords": [
15
16
  "claude",
@@ -21,17 +22,26 @@
21
22
  "git",
22
23
  "dashboard"
23
24
  ],
25
+ "author": "Akshat Sahu",
24
26
  "license": "MIT",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/Akshat2634/Codelens-AI.git"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/Akshat2634/Codelens-AI/issues"
33
+ },
34
+ "homepage": "https://github.com/Akshat2634/Codelens-AI#readme",
25
35
  "engines": {
26
36
  "node": ">=18.0.0"
27
37
  },
28
38
  "dependencies": {
29
39
  "commander": "^13.0.0",
30
40
  "express": "^5.0.0",
31
- "open": "^10.0.0",
32
- "playwright": "^1.58.2"
41
+ "open": "^10.0.0"
33
42
  },
34
43
  "devDependencies": {
35
- "@playwright/test": "^1.56.1"
44
+ "@playwright/test": "^1.56.1",
45
+ "playwright": "^1.58.2"
36
46
  }
37
47
  }
@@ -360,8 +360,8 @@ function mergeSubagentIntoSession(parent, sub) {
360
360
  parent.cost.cacheCreationCost += sub.cost.cacheCreationCost;
361
361
  parent.cost.totalCost += sub.cost.totalCost;
362
362
 
363
- parent.assistantMessageCount += sub.assistantMessageCount;
364
- parent.userMessageCount += sub.userMessageCount;
363
+ // Message counts intentionally NOT merged — we only report
364
+ // the main-conversation messages, not internal subagent chatter.
365
365
 
366
366
  // Merge model breakdown
367
367
  for (const [model, data] of Object.entries(sub.modelBreakdown)) {
@@ -457,10 +457,28 @@ export async function parseAllProjects(claudeDir, days, projectFilter) {
457
457
  }
458
458
  }
459
459
 
460
+ // Deduplicate sessions by sessionId (same session can appear in
461
+ // multiple project dirs, e.g. main repo vs worktree paths)
462
+ const seen = new Map();
463
+ for (const s of sessions) {
464
+ const id = s.sessionId;
465
+ if (!seen.has(id)) {
466
+ seen.set(id, s);
467
+ } else {
468
+ const existing = seen.get(id);
469
+ const existingMsgs = existing.userMessageCount + existing.assistantMessageCount;
470
+ const newMsgs = s.userMessageCount + s.assistantMessageCount;
471
+ if (newMsgs > existingMsgs) {
472
+ seen.set(id, s);
473
+ }
474
+ }
475
+ }
476
+ const deduped = Array.from(seen.values());
477
+
460
478
  // Sort by start time descending
461
- sessions.sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime());
479
+ deduped.sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime());
462
480
 
463
- return { sessions, fileIndex };
481
+ return { sessions: deduped, fileIndex };
464
482
  }
465
483
 
466
484
  export { calculateCost, getModelFamily, PRICING };
package/src/correlator.js CHANGED
@@ -1,70 +1,125 @@
1
1
  const FALLBACK_BUFFER_MS = 2 * 60 * 60 * 1000; // 2 hours for time-only fallback
2
2
 
3
+ function computeOverlappingLines(commits, sessionFiles) {
4
+ let linesAdded = 0;
5
+ let linesDeleted = 0;
6
+ for (const c of commits) {
7
+ for (const f of c.files) {
8
+ if (sessionFiles.has(f.path)) {
9
+ linesAdded += f.added;
10
+ linesDeleted += f.deleted;
11
+ }
12
+ }
13
+ }
14
+ return { linesAdded, linesDeleted };
15
+ }
16
+
17
+ /**
18
+ * Compute the temporal distance between a commit and a session.
19
+ * Returns the minimum absolute distance from the commit to the session's
20
+ * time range (0 if the commit falls within the session window).
21
+ */
22
+ function temporalDistance(commitMs, sessionStartMs, sessionEndMs) {
23
+ if (commitMs >= sessionStartMs && commitMs <= sessionEndMs) return 0;
24
+ return Math.min(
25
+ Math.abs(commitMs - sessionStartMs),
26
+ Math.abs(commitMs - sessionEndMs)
27
+ );
28
+ }
29
+
3
30
  /**
4
31
  * Correlate sessions to commits using file-based matching.
5
32
  *
33
+ * Uses a two-pass "nearest session wins" approach:
34
+ * 1. For each commit, find all candidate sessions (file overlap + time window)
35
+ * and assign it to the temporally closest one.
36
+ * 2. Build correlated results from those assignments.
37
+ *
6
38
  * Primary: match commits whose changed files overlap with session.filesWritten.
7
- * Time constraint: commit is on the same calendar day or the next day.
39
+ * Time constraint: commit is within [sessionStart, sessionEnd + 2 hours].
8
40
  * Fallback: for sessions with no filesWritten (chat-only), use time window
9
41
  * [sessionStart, sessionEnd + 2 hours].
10
42
  */
11
43
  export function correlateSessions(sessions, commitsByRepo) {
12
- const result = [];
13
- const claimedCommits = new Set();
44
+ // Phase 1: Build candidate map — for each commit, find the best session
45
+ // commitHash -> { session, hasFileOverlap }
46
+ const commitAssignment = new Map();
14
47
 
15
- // Sort sessions by end time so earlier sessions claim commits first
16
- const sorted = [...sessions].sort(
17
- (a, b) => new Date(a.endTime).getTime() - new Date(b.endTime).getTime()
18
- );
19
-
20
- for (const session of sorted) {
48
+ for (const session of sessions) {
21
49
  const repoAnalysis = commitsByRepo[session.repoPath];
22
50
  const repoCommits = repoAnalysis?.commits || [];
23
51
 
24
- const sessionStart = new Date(session.startTime).getTime();
25
- const sessionEnd = new Date(session.endTime).getTime();
52
+ const sessionStartMs = new Date(session.startTime).getTime();
53
+ const sessionEndMs = new Date(session.endTime).getTime();
26
54
  const sessionFiles = new Set(session.filesWritten || []);
55
+ const windowEnd = sessionEndMs + FALLBACK_BUFFER_MS;
27
56
 
28
- let matched;
57
+ for (const commit of repoCommits) {
58
+ // Time constraint: commit must fall within [sessionStart, sessionEnd + 2h]
59
+ if (commit.timestampMs < sessionStartMs || commit.timestampMs > windowEnd) continue;
29
60
 
30
- if (sessionFiles.size > 0) {
31
- // PRIMARY: File-based correlation
32
- // Time window: same calendar day as session, or next calendar day
33
- const sessionDay = new Date(session.startTime);
34
- const dayStart = new Date(sessionDay.getFullYear(), sessionDay.getMonth(), sessionDay.getDate()).getTime();
35
- const dayEnd = dayStart + 2 * 24 * 60 * 60 * 1000; // end of next calendar day
36
-
37
- matched = repoCommits.filter(c => {
38
- if (claimedCommits.has(c.hash)) return false;
39
- if (c.timestampMs < dayStart || c.timestampMs >= dayEnd) return false;
40
- // Check file overlap: any commit file matches a session file
41
- return c.files.some(f => sessionFiles.has(f.path));
42
- });
43
- } else {
44
- // FALLBACK: Time-based for chat-only sessions (no files written)
45
- const windowEnd = sessionEnd + FALLBACK_BUFFER_MS;
46
- matched = repoCommits.filter(c =>
47
- c.timestampMs >= sessionStart &&
48
- c.timestampMs <= windowEnd &&
49
- !claimedCommits.has(c.hash)
50
- );
61
+ const hasFileOverlap = sessionFiles.size > 0 &&
62
+ commit.files.some(f => sessionFiles.has(f.path));
63
+ const isChatOnly = sessionFiles.size === 0;
64
+
65
+ // Must have file overlap, or be a chat-only session (time-based fallback)
66
+ if (!hasFileOverlap && !isChatOnly) continue;
67
+
68
+ const distance = temporalDistance(commit.timestampMs, sessionStartMs, sessionEndMs);
69
+ const existing = commitAssignment.get(commit.hash);
70
+
71
+ if (!existing) {
72
+ commitAssignment.set(commit.hash, { session, hasFileOverlap, distance });
73
+ } else {
74
+ // Prefer file-based match over time-only match
75
+ if (hasFileOverlap && !existing.hasFileOverlap) {
76
+ commitAssignment.set(commit.hash, { session, hasFileOverlap, distance });
77
+ } else if (hasFileOverlap === existing.hasFileOverlap && distance < existing.distance) {
78
+ // Same match type — prefer temporally closer session
79
+ commitAssignment.set(commit.hash, { session, hasFileOverlap, distance });
80
+ }
81
+ }
51
82
  }
83
+ }
52
84
 
53
- // Claim matched commits
54
- for (const c of matched) {
55
- claimedCommits.add(c.hash);
85
+ // Phase 2: Group commits by assigned session
86
+ const sessionCommits = new Map(); // sessionId -> commit[]
87
+ for (const [hash, { session }] of commitAssignment) {
88
+ if (!sessionCommits.has(session.sessionId)) {
89
+ sessionCommits.set(session.sessionId, []);
90
+ }
91
+ // Find the actual commit object from the repo
92
+ const repoAnalysis = commitsByRepo[session.repoPath];
93
+ const commit = repoAnalysis?.commits?.find(c => c.hash === hash);
94
+ if (commit) {
95
+ sessionCommits.get(session.sessionId).push(commit);
56
96
  }
97
+ }
57
98
 
58
- const linesAdded = matched.reduce((s, c) => s + c.totalAdded, 0);
59
- const linesDeleted = matched.reduce((s, c) => s + c.totalDeleted, 0);
99
+ // Phase 3: Build correlated results
100
+ const claimedCommits = new Set(commitAssignment.keys());
101
+ const result = [];
102
+
103
+ for (const session of sessions) {
104
+ const sessionFiles = new Set(session.filesWritten || []);
105
+ const matched = sessionCommits.get(session.sessionId) || [];
106
+
107
+ let linesAdded, linesDeleted;
108
+ if (sessionFiles.size > 0) {
109
+ ({ linesAdded, linesDeleted } = computeOverlappingLines(matched, sessionFiles));
110
+ } else {
111
+ linesAdded = matched.reduce((s, c) => s + c.totalAdded, 0);
112
+ linesDeleted = matched.reduce((s, c) => s + c.totalDeleted, 0);
113
+ }
60
114
  const netLines = linesAdded - linesDeleted;
61
- const filesChanged = new Set(matched.flatMap(c => c.files.map(f => f.path))).size;
115
+ const filesChanged = sessionFiles.size > 0
116
+ ? new Set(matched.flatMap(c => c.files.filter(f => sessionFiles.has(f.path)).map(f => f.path))).size
117
+ : new Set(matched.flatMap(c => c.files.map(f => f.path))).size;
62
118
  const commitsOnMain = matched.filter(c => c.onMain).length;
63
119
 
64
120
  const messageCount = session.userMessageCount + session.assistantMessageCount;
65
121
  const isOrphaned = messageCount > 10 && matched.length === 0;
66
122
 
67
- // Calculate which session files were committed vs not
68
123
  const committedFiles = new Set(matched.flatMap(c => c.files.map(f => f.path)));
69
124
  const uncommittedFiles = [...sessionFiles].filter(f => !committedFiles.has(f));
70
125
 
@@ -96,7 +151,7 @@ export function correlateSessions(sessions, commitsByRepo) {
96
151
  }
97
152
  }
98
153
 
99
- // Re-sort result by start time descending (most recent first for display)
154
+ // Sort result by start time descending (most recent first for display)
100
155
  result.sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime());
101
156
 
102
157
  return { correlatedSessions: result, organicCommits };
package/src/index.js CHANGED
@@ -9,8 +9,11 @@ import { correlateSessions } from './correlator.js';
9
9
  import { computeMetrics } from './metrics.js';
10
10
  import { loadCache, saveCache, deleteCache, getStaleFiles } from './cache.js';
11
11
  import { createServer } from './server.js';
12
+ import { readFileSync } from 'node:fs';
12
13
 
13
- const VERSION = '0.1.1';
14
+ const { version: VERSION } = JSON.parse(
15
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8')
16
+ );
14
17
 
15
18
  async function main() {
16
19
  const program = new Command();
package/src/metrics.js CHANGED
@@ -406,6 +406,9 @@ export function computeMetrics(correlatedSessions, organicCommits, commitsByRepo
406
406
  // ---- Model breakdown ----
407
407
  const modelBreakdown = {};
408
408
  for (const session of correlatedSessions) {
409
+ const sessionTotalTokens = Object.values(session.modelBreakdown)
410
+ .reduce((s, d) => s + d.tokens, 0);
411
+
409
412
  for (const [model, data] of Object.entries(session.modelBreakdown)) {
410
413
  const family = getModelFamily(model) || 'unknown';
411
414
  if (!modelBreakdown[family]) {
@@ -413,16 +416,15 @@ export function computeMetrics(correlatedSessions, organicCommits, commitsByRepo
413
416
  }
414
417
  modelBreakdown[family].cost += data.cost;
415
418
  modelBreakdown[family].tokens += data.tokens;
419
+
420
+ // Distribute sessions and commits proportionally by token share
421
+ const share = sessionTotalTokens > 0 ? data.tokens / sessionTotalTokens : 0;
422
+ modelBreakdown[family].sessions += share;
423
+ modelBreakdown[family].commits += session.commitCount * share;
416
424
  }
417
- // Count sessions/commits per primary model
418
- const primaryFamily = getModelFamily(session.model) || 'unknown';
419
- if (!modelBreakdown[primaryFamily]) {
420
- modelBreakdown[primaryFamily] = { cost: 0, tokens: 0, sessions: 0, commits: 0, avgCostPerCommit: null };
421
- }
422
- modelBreakdown[primaryFamily].sessions++;
423
- modelBreakdown[primaryFamily].commits += session.commitCount;
424
425
  }
425
426
  for (const data of Object.values(modelBreakdown)) {
427
+ data.sessions = Math.round(data.sessions);
426
428
  data.avgCostPerCommit = data.commits > 0 ? data.cost / data.commits : null;
427
429
  data.tokensPerCommit = data.commits > 0 ? Math.round(data.tokens / data.commits) : null;
428
430
  }
@@ -1,9 +0,0 @@
1
- import { defineConfig } from '@playwright/test';
2
-
3
- export default defineConfig({
4
- testDir: './tests',
5
- timeout: 30000,
6
- use: {
7
- baseURL: 'http://localhost:3457',
8
- },
9
- });