runwork 0.6.1 → 0.8.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.
Files changed (80) hide show
  1. package/dist/__tests__/install-scripts.test.d.ts +1 -0
  2. package/dist/__tests__/install-scripts.test.js +247 -0
  3. package/dist/agents/__tests__/claude-code-plugin.test.d.ts +1 -0
  4. package/dist/agents/__tests__/claude-code-plugin.test.js +47 -0
  5. package/dist/agents/__tests__/claude-code-stats.test.js +143 -78
  6. package/dist/agents/__tests__/claude-desktop-plugin-tree.test.d.ts +1 -0
  7. package/dist/agents/__tests__/claude-desktop-plugin-tree.test.js +161 -0
  8. package/dist/agents/__tests__/claude-desktop-plugin.test.d.ts +1 -0
  9. package/dist/agents/__tests__/claude-desktop-plugin.test.js +117 -0
  10. package/dist/agents/__tests__/claude-desktop-rpm.test.d.ts +1 -0
  11. package/dist/agents/__tests__/claude-desktop-rpm.test.js +126 -0
  12. package/dist/agents/__tests__/codex-instructions.test.d.ts +1 -0
  13. package/dist/agents/__tests__/codex-instructions.test.js +57 -0
  14. package/dist/agents/__tests__/codex-stats.test.js +9 -0
  15. package/dist/agents/__tests__/graceful-degradation.test.js +3 -3
  16. package/dist/agents/__tests__/intro-skill.test.js +11 -2
  17. package/dist/agents/__tests__/skill-slug.test.d.ts +1 -0
  18. package/dist/agents/__tests__/skill-slug.test.js +77 -0
  19. package/dist/agents/claude-code.d.ts +3 -1
  20. package/dist/agents/claude-code.js +233 -58
  21. package/dist/agents/claude-desktop-plugin-tree.d.ts +44 -0
  22. package/dist/agents/claude-desktop-plugin-tree.js +92 -0
  23. package/dist/agents/claude-desktop.d.ts +20 -1
  24. package/dist/agents/claude-desktop.js +238 -61
  25. package/dist/agents/cline.d.ts +3 -1
  26. package/dist/agents/cline.js +44 -2
  27. package/dist/agents/codex.d.ts +3 -1
  28. package/dist/agents/codex.js +85 -14
  29. package/dist/agents/cursor.d.ts +12 -1
  30. package/dist/agents/cursor.js +98 -25
  31. package/dist/agents/gemini.d.ts +3 -1
  32. package/dist/agents/gemini.js +42 -4
  33. package/dist/agents/generic-adapter.d.ts +3 -1
  34. package/dist/agents/generic-adapter.js +59 -4
  35. package/dist/agents/intro-skill.js +77 -31
  36. package/dist/agents/types.d.ts +42 -2
  37. package/dist/agents/types.js +61 -6
  38. package/dist/agents/utils/instruction-hint.d.ts +10 -0
  39. package/dist/agents/utils/instruction-hint.js +46 -0
  40. package/dist/agents/utils/json-config.d.ts +6 -1
  41. package/dist/agents/utils/json-config.js +31 -4
  42. package/dist/agents/windsurf.d.ts +3 -1
  43. package/dist/agents/windsurf.js +37 -2
  44. package/dist/commands/__tests__/sync-telemetry.test.d.ts +1 -0
  45. package/dist/commands/__tests__/sync-telemetry.test.js +281 -0
  46. package/dist/commands/__tests__/upgrade.test.d.ts +1 -0
  47. package/dist/commands/__tests__/upgrade.test.js +174 -0
  48. package/dist/commands/build-plugin.d.ts +2 -0
  49. package/dist/commands/build-plugin.js +135 -0
  50. package/dist/commands/init.d.ts +8 -2
  51. package/dist/commands/init.js +19 -7
  52. package/dist/commands/sync-telemetry.d.ts +33 -0
  53. package/dist/commands/sync-telemetry.js +186 -0
  54. package/dist/commands/sync.d.ts +1 -0
  55. package/dist/commands/sync.js +84 -118
  56. package/dist/commands/uninstall.d.ts +2 -0
  57. package/dist/commands/uninstall.js +145 -0
  58. package/dist/commands/upgrade.d.ts +12 -0
  59. package/dist/commands/upgrade.js +67 -16
  60. package/dist/generated/bundled-types.js +36 -36
  61. package/dist/generated/version.d.ts +1 -1
  62. package/dist/generated/version.js +1 -1
  63. package/dist/health/__tests__/cli-distribution-checks.test.d.ts +1 -0
  64. package/dist/health/__tests__/cli-distribution-checks.test.js +199 -0
  65. package/dist/health/checks.d.ts +2 -0
  66. package/dist/health/checks.js +131 -18
  67. package/dist/health/runner.js +6 -2
  68. package/dist/index.js +4 -0
  69. package/dist/sync/executor.d.ts +2 -0
  70. package/dist/sync/executor.js +8 -4
  71. package/dist/types.d.ts +2 -0
  72. package/dist/ui/banner.js +15 -6
  73. package/dist/utils/__tests__/sqlite.test.js +84 -72
  74. package/dist/utils/sqlite-adapter.d.ts +48 -0
  75. package/dist/utils/sqlite-adapter.js +147 -0
  76. package/dist/utils/sqlite.d.ts +12 -5
  77. package/dist/utils/sqlite.js +12 -22
  78. package/dist/utils/zip.d.ts +6 -0
  79. package/dist/utils/zip.js +28 -3
  80. package/package.json +2 -4
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Integration tests for the Runwork install scripts.
3
+ *
4
+ * install.sh runs end-to-end against a local HTTP server that serves a fake
5
+ * release manifest and a tar.gz for the current host platform. install.ps1 is
6
+ * checked statically (grep of invariants) because PowerShell is not available
7
+ * on the Unix runners that execute this suite.
8
+ *
9
+ * Design note: install.sh uses curl to fetch from the in-process Node HTTP
10
+ * server, so we MUST run the child process asynchronously. Using execFileSync
11
+ * would block the Node event loop, preventing the HTTP server from responding
12
+ * to curl and deadlocking the test.
13
+ */
14
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
15
+ import { execFileSync, spawn } from 'node:child_process';
16
+ import { createServer } from 'node:http';
17
+ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, statSync, writeFileSync, } from 'node:fs';
18
+ import { tmpdir } from 'node:os';
19
+ import { join } from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { createHash } from 'node:crypto';
22
+ const INSTALL_SH = fileURLToPath(new URL('../../install.sh', import.meta.url));
23
+ const INSTALL_PS1 = fileURLToPath(new URL('../../install.ps1', import.meta.url));
24
+ function detectHostPlatform() {
25
+ const osMap = { darwin: 'darwin', linux: 'linux' };
26
+ const archMap = { x64: 'x64', arm64: 'arm64' };
27
+ const os = osMap[process.platform];
28
+ const arch = archMap[process.arch];
29
+ if (!os || !arch) {
30
+ throw new Error(`install.sh integration test requires darwin/linux and x64/arm64; got ${process.platform}/${process.arch}`);
31
+ }
32
+ return { os, arch, platform: `${os}-${arch}` };
33
+ }
34
+ function sha256Hex(data) {
35
+ return createHash('sha256').update(data).digest('hex');
36
+ }
37
+ function runInstallSh(env) {
38
+ return new Promise((resolvePromise) => {
39
+ const child = spawn('sh', [INSTALL_SH], {
40
+ env,
41
+ stdio: ['ignore', 'pipe', 'pipe'],
42
+ });
43
+ let stdout = '';
44
+ let stderr = '';
45
+ child.stdout.on('data', (chunk) => {
46
+ stdout += chunk.toString();
47
+ });
48
+ child.stderr.on('data', (chunk) => {
49
+ stderr += chunk.toString();
50
+ });
51
+ child.on('error', (err) => {
52
+ resolvePromise({ status: -1, stdout, stderr: stderr + `\n[spawn error] ${err.message}` });
53
+ });
54
+ child.on('close', (code) => {
55
+ resolvePromise({ status: code ?? -1, stdout, stderr });
56
+ });
57
+ });
58
+ }
59
+ describe('install.sh (end-to-end)', () => {
60
+ let workDir;
61
+ let serverDir;
62
+ let server;
63
+ let serverUrl;
64
+ let platformInfo;
65
+ let archivePath;
66
+ beforeEach(async () => {
67
+ platformInfo = detectHostPlatform();
68
+ workDir = mkdtempSync(join(tmpdir(), 'runwork-install-test-'));
69
+ serverDir = join(workDir, 'server');
70
+ mkdirSync(serverDir, { recursive: true });
71
+ // Fake binary that prints a recognizable version string.
72
+ const binaryName = `runwork-${platformInfo.platform}`;
73
+ const binarySource = join(workDir, 'binary-source');
74
+ mkdirSync(binarySource, { recursive: true });
75
+ const binaryPath = join(binarySource, binaryName);
76
+ writeFileSync(binaryPath, '#!/bin/sh\necho "runwork 99.99.99 (test)"\n');
77
+ chmodSync(binaryPath, 0o755);
78
+ // Pack the binary into a tar.gz at the manifest path.
79
+ const archiveName = `${binaryName}.tar.gz`;
80
+ const releasesDir = join(serverDir, 'cli', 'releases', '99.99.99');
81
+ mkdirSync(releasesDir, { recursive: true });
82
+ archivePath = join(releasesDir, archiveName);
83
+ execFileSync('tar', ['-czf', archivePath, binaryName], { cwd: binarySource });
84
+ const sha = sha256Hex(readFileSync(archivePath));
85
+ // Write the manifest consumed by install.sh.
86
+ const manifest = {
87
+ name: 'runwork',
88
+ version: '99.99.99',
89
+ publishedAt: new Date().toISOString(),
90
+ artifacts: {
91
+ [platformInfo.platform]: {
92
+ path: `/cli/releases/99.99.99/${archiveName}`,
93
+ sha256: sha,
94
+ },
95
+ },
96
+ };
97
+ writeFileSync(join(serverDir, 'cli', 'latest.json'), JSON.stringify(manifest, null, 2) + '\n');
98
+ // Minimal static HTTP server rooted at serverDir.
99
+ server = createServer((req, res) => {
100
+ const requestPath = decodeURIComponent(req.url ?? '/').replace(/^\/+/, '');
101
+ const filePath = join(serverDir, requestPath);
102
+ if (!filePath.startsWith(serverDir) ||
103
+ !existsSync(filePath) ||
104
+ statSync(filePath).isDirectory()) {
105
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
106
+ res.end('not found');
107
+ return;
108
+ }
109
+ const body = readFileSync(filePath);
110
+ res.writeHead(200, {
111
+ 'Content-Type': 'application/octet-stream',
112
+ 'Content-Length': body.length,
113
+ });
114
+ res.end(body);
115
+ });
116
+ await new Promise((resolvePromise) => {
117
+ server.listen(0, '127.0.0.1', () => {
118
+ const addr = server.address();
119
+ if (addr && typeof addr === 'object') {
120
+ serverUrl = `http://127.0.0.1:${addr.port}`;
121
+ }
122
+ resolvePromise();
123
+ });
124
+ });
125
+ });
126
+ afterEach(async () => {
127
+ await new Promise((resolvePromise) => {
128
+ server.close(() => resolvePromise());
129
+ });
130
+ rmSync(workDir, { recursive: true, force: true });
131
+ });
132
+ function envFor(overrides) {
133
+ return {
134
+ ...process.env,
135
+ HOME: workDir,
136
+ RUNWORK_DOWNLOAD_BASE_URL: serverUrl,
137
+ ...overrides,
138
+ };
139
+ }
140
+ it('installs the binary to the canonical location and symlinks it onto PATH', async () => {
141
+ const installDir = join(workDir, 'install');
142
+ const linkDir = join(workDir, 'link');
143
+ const result = await runInstallSh(envFor({
144
+ RUNWORK_INSTALL_DIR: installDir,
145
+ RUNWORK_BIN_LINK_DIR: linkDir,
146
+ }));
147
+ expect(result.status, `installer failed:\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`).toBe(0);
148
+ expect(result.stdout).toContain('99.99.99');
149
+ expect(result.stdout).toContain(platformInfo.platform);
150
+ const installedBinary = join(installDir, 'runwork');
151
+ expect(existsSync(installedBinary)).toBe(true);
152
+ expect(statSync(installedBinary).mode & 0o111).toBeGreaterThan(0);
153
+ const linkPath = join(linkDir, 'runwork');
154
+ expect(existsSync(linkPath)).toBe(true);
155
+ expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);
156
+ expect(readlinkSync(linkPath)).toBe(installedBinary);
157
+ const versionOutput = execFileSync(installedBinary, [], { encoding: 'utf-8' });
158
+ expect(versionOutput).toContain('99.99.99');
159
+ });
160
+ it('defaults install location to $HOME/.runwork/bin when RUNWORK_INSTALL_DIR is unset', async () => {
161
+ const result = await runInstallSh(envFor({
162
+ RUNWORK_BIN_LINK_DIR: join(workDir, 'link'),
163
+ }));
164
+ expect(result.status, `installer failed:\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`).toBe(0);
165
+ const defaultBinary = join(workDir, '.runwork', 'bin', 'runwork');
166
+ expect(existsSync(defaultBinary)).toBe(true);
167
+ });
168
+ it('aborts on sha256 mismatch and leaves the install directory untouched', async () => {
169
+ // Tamper with the archive the server is about to serve.
170
+ writeFileSync(archivePath, Buffer.from('tampered payload'));
171
+ const installDir = join(workDir, 'install');
172
+ const result = await runInstallSh(envFor({
173
+ RUNWORK_INSTALL_DIR: installDir,
174
+ RUNWORK_BIN_LINK_DIR: join(workDir, 'link'),
175
+ }));
176
+ expect(result.status).not.toBe(0);
177
+ expect(result.stderr).toContain('sha256 mismatch');
178
+ expect(existsSync(join(installDir, 'runwork'))).toBe(false);
179
+ });
180
+ it('reports a clear error when the manifest is unreachable', async () => {
181
+ rmSync(join(serverDir, 'cli', 'latest.json'));
182
+ const result = await runInstallSh(envFor({
183
+ RUNWORK_INSTALL_DIR: join(workDir, 'install'),
184
+ RUNWORK_BIN_LINK_DIR: join(workDir, 'link'),
185
+ }));
186
+ expect(result.status).not.toBe(0);
187
+ expect(result.stderr).toContain('failed to fetch release manifest');
188
+ });
189
+ it('reports a clear error when the manifest has no artifact for the host platform', async () => {
190
+ const fakePlatform = platformInfo.platform === 'linux-x64' ? 'linux-arm64' : 'linux-x64';
191
+ const manifest = {
192
+ name: 'runwork',
193
+ version: '99.99.99',
194
+ publishedAt: new Date().toISOString(),
195
+ artifacts: {
196
+ [fakePlatform]: {
197
+ path: `/cli/releases/99.99.99/runwork-${fakePlatform}.tar.gz`,
198
+ sha256: 'deadbeef',
199
+ },
200
+ },
201
+ };
202
+ writeFileSync(join(serverDir, 'cli', 'latest.json'), JSON.stringify(manifest, null, 2));
203
+ const result = await runInstallSh(envFor({
204
+ RUNWORK_INSTALL_DIR: join(workDir, 'install'),
205
+ RUNWORK_BIN_LINK_DIR: join(workDir, 'link'),
206
+ }));
207
+ expect(result.status).not.toBe(0);
208
+ expect(result.stderr).toContain('no artifact entry for platform');
209
+ });
210
+ });
211
+ describe('install.ps1 (static invariants)', () => {
212
+ let contents;
213
+ beforeEach(() => {
214
+ contents = readFileSync(INSTALL_PS1, 'utf-8');
215
+ });
216
+ it('exists alongside install.sh', () => {
217
+ expect(existsSync(INSTALL_PS1)).toBe(true);
218
+ });
219
+ it('resolves the manifest against runwork.ai/cli/latest.json by default', () => {
220
+ expect(contents).toContain("'https://runwork.ai'");
221
+ expect(contents).toContain('/cli/latest.json');
222
+ });
223
+ it('honors the RUNWORK_* env var overrides documented in the plan', () => {
224
+ expect(contents).toContain('RUNWORK_VERSION');
225
+ expect(contents).toContain('RUNWORK_INSTALL_DIR');
226
+ expect(contents).toContain('RUNWORK_DOWNLOAD_BASE_URL');
227
+ });
228
+ it('verifies sha256 with Get-FileHash -Algorithm SHA256', () => {
229
+ expect(contents).toContain('Get-FileHash');
230
+ expect(contents).toContain('SHA256');
231
+ expect(contents).toContain('sha256 mismatch');
232
+ });
233
+ it('targets the canonical Windows install location under %USERPROFILE%\\.runwork\\bin', () => {
234
+ expect(contents).toMatch(/\$env:USERPROFILE/);
235
+ expect(contents).toMatch(/['"]\.runwork\\bin['"]/);
236
+ });
237
+ it('modifies the user PATH scope only (never machine)', () => {
238
+ expect(contents).toContain("'User'");
239
+ expect(contents).not.toContain("'Machine'");
240
+ });
241
+ it('downloads release artifacts from /cli/releases/<version>/<artifact>', () => {
242
+ expect(contents).toMatch(/\/cli\/releases\//);
243
+ });
244
+ it('does not escalate to admin', () => {
245
+ expect(contents).not.toMatch(/Start-Process.*-Verb\s+RunAs/i);
246
+ });
247
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,47 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { mkdtempSync, readFileSync, rmSync } from 'fs';
3
+ import { join } from 'path';
4
+ import { tmpdir } from 'os';
5
+ let mockHomeDir = '/tmp/runwork-cli-tests';
6
+ vi.mock('os', async () => {
7
+ const actual = await vi.importActual('os');
8
+ return {
9
+ ...actual,
10
+ homedir: vi.fn(() => mockHomeDir),
11
+ };
12
+ });
13
+ import { ClaudeCodeAdapter } from '../claude-code.js';
14
+ describe('ClaudeCodeAdapter MCP plugin files', () => {
15
+ let tempHomeDir;
16
+ beforeEach(() => {
17
+ tempHomeDir = mkdtempSync(join(tmpdir(), 'runwork-cli-claude-code-'));
18
+ mockHomeDir = tempHomeDir;
19
+ });
20
+ afterEach(() => {
21
+ rmSync(tempHomeDir, { recursive: true, force: true });
22
+ });
23
+ it('writes the Runwork MCP config into the marketplace plugin directory', async () => {
24
+ const adapter = new ClaudeCodeAdapter();
25
+ const server = {
26
+ name: 'Runwork',
27
+ url: 'https://runwork.ai/api/workspaces/test/mcp',
28
+ transport: 'streamable-http',
29
+ headers: {
30
+ Authorization: 'Bearer test-token',
31
+ },
32
+ description: 'Runwork workspace tools',
33
+ };
34
+ await adapter.writeMcpServers([server], 'user');
35
+ const cacheMcpPath = join(tempHomeDir, '.claude', 'plugins', 'cache', 'runwork', 'runwork', '1.0.0', '.mcp.json');
36
+ const marketplaceMcpPath = join(tempHomeDir, '.claude', 'plugins', 'marketplaces', 'runwork', 'plugins', 'runwork', '.mcp.json');
37
+ const cacheConfig = JSON.parse(readFileSync(cacheMcpPath, 'utf-8'));
38
+ const marketplaceConfig = JSON.parse(readFileSync(marketplaceMcpPath, 'utf-8'));
39
+ expect(marketplaceConfig).toEqual(cacheConfig);
40
+ expect(marketplaceConfig).toMatchObject({
41
+ 'Runwork': {
42
+ type: 'http',
43
+ url: 'https://runwork.ai/api/workspaces/test/mcp',
44
+ },
45
+ });
46
+ });
47
+ });
@@ -2,7 +2,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
3
3
  import { homedir } from 'os';
4
4
  import { execFileSync } from 'child_process';
5
- import path from 'path';
6
5
  vi.mock('fs');
7
6
  vi.mock('os');
8
7
  vi.mock('child_process');
@@ -16,115 +15,181 @@ vi.mock('../utils/instruction-hint.js', () => ({
16
15
  writeHintToFile: vi.fn(),
17
16
  }));
18
17
  import { ClaudeCodeAdapter } from '../claude-code.js';
19
- const FIXTURE_STATS = path.resolve(__dirname, './fixtures/claude-code/stats-cache.json');
20
- // Read the real fixture once for use in mocks
21
- // (We read it at import time before mocks interfere, via a direct require)
22
- // eslint-disable-next-line @typescript-eslint/no-require-imports
23
- const realFs = require('fs');
24
- const fixtureContent = realFs.readFileSync(FIXTURE_STATS, 'utf-8');
18
+ const HOME = '/mock-home';
19
+ const CLAUDE_DIR = `${HOME}/.claude`;
20
+ const PROJECTS_DIR = `${CLAUDE_DIR}/projects`;
25
21
  let adapter;
26
22
  beforeEach(() => {
27
23
  vi.restoreAllMocks();
28
- vi.mocked(homedir).mockReturnValue('/mock-home');
24
+ vi.mocked(homedir).mockReturnValue(HOME);
29
25
  adapter = new ClaudeCodeAdapter();
30
26
  });
31
27
  // Helper: make existsSync return true only for specified paths
32
28
  function mockExistsPaths(paths) {
33
29
  vi.mocked(existsSync).mockImplementation((p) => paths.includes(p));
34
30
  }
31
+ function jsonl(entries) {
32
+ return entries.map(e => {
33
+ const obj = { type: e.type };
34
+ if (e.ts)
35
+ obj.timestamp = e.ts;
36
+ if (e.type === 'user') {
37
+ obj.message = { role: 'user', content: e.content ?? 'hello' };
38
+ }
39
+ else if (e.type === 'assistant') {
40
+ obj.message = {
41
+ role: 'assistant',
42
+ content: e.content ?? [{ type: 'text', text: 'hi' }],
43
+ ...(e.usage ? { usage: e.usage } : {}),
44
+ };
45
+ }
46
+ return JSON.stringify(obj);
47
+ }).join('\n');
48
+ }
35
49
  describe('ClaudeCodeAdapter.readUsageStats', () => {
36
- it('parses stats-cache.json and returns correct totals when lastSyncAt is null', async () => {
37
- mockExistsPaths([
38
- '/mock-home/.claude',
39
- '/mock-home/.claude/stats-cache.json',
40
- ]);
41
- vi.mocked(readFileSync).mockReturnValue(fixtureContent);
50
+ it('parses an active session JSONL and aggregates messages, tool calls, and tokens', async () => {
51
+ mockExistsPaths([CLAUDE_DIR, PROJECTS_DIR]);
52
+ vi.mocked(readdirSync).mockImplementation((p) => {
53
+ if (p === PROJECTS_DIR)
54
+ return ['-Users-test-project'];
55
+ if (p === `${PROJECTS_DIR}/-Users-test-project`) {
56
+ return ['sess-a.jsonl'];
57
+ }
58
+ return [];
59
+ });
60
+ vi.mocked(statSync).mockReturnValue({ mtimeMs: 2_000_000_000_000 });
61
+ vi.mocked(readFileSync).mockReturnValue(jsonl([
62
+ { type: 'user', ts: '2026-04-13T22:00:00.000Z' },
63
+ { type: 'assistant', ts: '2026-04-13T22:00:05.000Z',
64
+ content: [{ type: 'text', text: 'response' }],
65
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_input_tokens: 1000 } },
66
+ { type: 'assistant', ts: '2026-04-13T22:00:10.000Z',
67
+ content: [{ type: 'tool_use', name: 'Read' }, { type: 'tool_use', name: 'Edit' }],
68
+ usage: { input_tokens: 50, output_tokens: 20 } },
69
+ { type: 'user', ts: '2026-04-13T22:00:15.000Z' },
70
+ // Lines without timestamps are ignored
71
+ { type: 'permission-mode' },
72
+ ]));
42
73
  const stats = await adapter.readUsageStats(null);
43
74
  expect(stats).not.toBeNull();
44
- // All 6 days: 15+22+0+40+10+35 = 122 messages
45
- expect(stats.messageCount).toBe(122);
46
- // 2+3+0+4+1+5 = 15 sessions
47
- expect(stats.sessionCount).toBe(15);
48
- // 8+12+0+25+5+18 = 68 tool calls
49
- expect(stats.toolCallCount).toBe(68);
50
75
  expect(stats.hasNewActivity).toBe(true);
76
+ expect(stats.sessionCount).toBe(1);
77
+ expect(stats.messageCount).toBe(4); // 2 user + 2 assistant
78
+ expect(stats.toolCallCount).toBe(2);
79
+ expect(stats.tokensUsed).toBe(220); // 150 input + 70 output (cache_read in extra)
80
+ expect(stats.lastActiveAt).toBe('2026-04-13T22:00:15.000Z');
81
+ expect(stats.extra).toEqual({ inputTokens: 150, outputTokens: 70, cacheReadTokens: 1000 });
51
82
  });
52
- it('filters days after lastSyncAt date', async () => {
53
- mockExistsPaths([
54
- '/mock-home/.claude',
55
- '/mock-home/.claude/stats-cache.json',
56
- ]);
57
- vi.mocked(readFileSync).mockReturnValue(fixtureContent);
58
- const stats = await adapter.readUsageStats('2026-03-27T00:00:00Z');
83
+ it('filters out entries with timestamp <= lastSyncAt within the same file', async () => {
84
+ const sinceIso = '2026-04-13T20:00:00.000Z';
85
+ mockExistsPaths([CLAUDE_DIR, PROJECTS_DIR]);
86
+ vi.mocked(readdirSync).mockImplementation((p) => {
87
+ if (p === PROJECTS_DIR)
88
+ return ['cwd'];
89
+ if (p === `${PROJECTS_DIR}/cwd`)
90
+ return ['s.jsonl'];
91
+ return [];
92
+ });
93
+ vi.mocked(statSync).mockReturnValue({ mtimeMs: Date.parse('2026-04-13T22:00:00Z') });
94
+ vi.mocked(readFileSync).mockReturnValue(jsonl([
95
+ { type: 'user', ts: '2026-04-13T19:00:00.000Z' }, // before sync, ignored
96
+ { type: 'assistant', ts: '2026-04-13T19:30:00.000Z',
97
+ usage: { input_tokens: 999, output_tokens: 999 } }, // before sync, tokens NOT counted
98
+ { type: 'user', ts: '2026-04-13T21:00:00.000Z' }, // after sync, counted
99
+ { type: 'assistant', ts: '2026-04-13T21:00:05.000Z',
100
+ content: [{ type: 'tool_use', name: 'Read' }],
101
+ usage: { input_tokens: 10, output_tokens: 5 } },
102
+ ]));
103
+ const stats = await adapter.readUsageStats(sinceIso);
59
104
  expect(stats).not.toBeNull();
60
- // Days after 2026-03-27: 28, 29, 30 => 40+10+35 = 85
61
- expect(stats.messageCount).toBe(85);
62
- // 4+1+5 = 10
63
- expect(stats.sessionCount).toBe(10);
64
- // 25+5+18 = 48
65
- expect(stats.toolCallCount).toBe(48);
105
+ expect(stats.messageCount).toBe(2); // only post-sync entries
106
+ expect(stats.toolCallCount).toBe(1);
107
+ expect(stats.tokensUsed).toBe(15); // 10 + 5, pre-sync 999+999 ignored
108
+ expect(stats.sessionCount).toBe(1);
66
109
  });
67
- it('returns null when all data is before lastSyncAt', async () => {
68
- mockExistsPaths([
69
- '/mock-home/.claude',
70
- '/mock-home/.claude/stats-cache.json',
71
- ]);
72
- vi.mocked(readFileSync).mockReturnValue(fixtureContent);
73
- const stats = await adapter.readUsageStats('2099-01-01T00:00:00Z');
110
+ it('skips JSONL files with mtime <= lastSyncAt without parsing them', async () => {
111
+ const sinceIso = '2026-04-13T20:00:00.000Z';
112
+ mockExistsPaths([CLAUDE_DIR, PROJECTS_DIR]);
113
+ vi.mocked(readdirSync).mockImplementation((p) => {
114
+ if (p === PROJECTS_DIR)
115
+ return ['cwd'];
116
+ if (p === `${PROJECTS_DIR}/cwd`)
117
+ return ['stale.jsonl'];
118
+ return [];
119
+ });
120
+ // mtime is BEFORE sinceMs - file should be skipped entirely
121
+ vi.mocked(statSync).mockReturnValue({ mtimeMs: Date.parse('2026-04-13T18:00:00Z') });
122
+ const readSpy = vi.mocked(readFileSync);
123
+ const stats = await adapter.readUsageStats(sinceIso);
74
124
  expect(stats).toBeNull();
125
+ expect(readSpy).not.toHaveBeenCalled();
75
126
  });
76
- it('returns null when ~/.claude does not exist', async () => {
77
- mockExistsPaths([]);
127
+ it('counts multiple sessions across multiple cwd directories', async () => {
128
+ mockExistsPaths([CLAUDE_DIR, PROJECTS_DIR]);
129
+ vi.mocked(readdirSync).mockImplementation((p) => {
130
+ const path = p;
131
+ if (path === PROJECTS_DIR) {
132
+ return ['-Users-a-proj1', '-Users-a-proj2'];
133
+ }
134
+ if (path === `${PROJECTS_DIR}/-Users-a-proj1`) {
135
+ return ['s1.jsonl'];
136
+ }
137
+ if (path === `${PROJECTS_DIR}/-Users-a-proj2`) {
138
+ return ['s2.jsonl', 's3.jsonl'];
139
+ }
140
+ return [];
141
+ });
142
+ vi.mocked(statSync).mockReturnValue({ mtimeMs: 2_000_000_000_000 });
143
+ vi.mocked(readFileSync).mockReturnValue(jsonl([
144
+ { type: 'user', ts: '2026-04-13T22:00:00.000Z' },
145
+ { type: 'assistant', ts: '2026-04-13T22:00:05.000Z' },
146
+ ]));
78
147
  const stats = await adapter.readUsageStats(null);
79
- expect(stats).toBeNull();
148
+ expect(stats).not.toBeNull();
149
+ expect(stats.sessionCount).toBe(3);
150
+ expect(stats.messageCount).toBe(6); // 2 messages * 3 sessions
80
151
  });
81
- it('returns null on corrupted stats-cache.json', async () => {
82
- mockExistsPaths([
83
- '/mock-home/.claude',
84
- '/mock-home/.claude/stats-cache.json',
85
- ]);
86
- vi.mocked(readFileSync).mockReturnValue('not valid json {{{');
152
+ it('returns null when ~/.claude does not exist', async () => {
153
+ mockExistsPaths([]);
87
154
  const stats = await adapter.readUsageStats(null);
88
155
  expect(stats).toBeNull();
89
156
  });
90
- it('returns null on unexpected schema (missing dailyActivity)', async () => {
91
- mockExistsPaths([
92
- '/mock-home/.claude',
93
- '/mock-home/.claude/stats-cache.json',
94
- ]);
95
- vi.mocked(readFileSync).mockReturnValue(JSON.stringify({ version: 2 }));
157
+ it('returns null when ~/.claude/projects does not exist', async () => {
158
+ mockExistsPaths([CLAUDE_DIR]);
96
159
  const stats = await adapter.readUsageStats(null);
97
160
  expect(stats).toBeNull();
98
161
  });
99
- it('returns null on empty dailyActivity array', async () => {
100
- mockExistsPaths([
101
- '/mock-home/.claude',
102
- '/mock-home/.claude/stats-cache.json',
103
- ]);
104
- vi.mocked(readFileSync).mockReturnValue(JSON.stringify({ version: 2, dailyActivity: [] }));
162
+ it('returns null when projects dir has no active sessions', async () => {
163
+ mockExistsPaths([CLAUDE_DIR, PROJECTS_DIR]);
164
+ vi.mocked(readdirSync).mockImplementation((p) => {
165
+ if (p === PROJECTS_DIR)
166
+ return [];
167
+ return [];
168
+ });
105
169
  const stats = await adapter.readUsageStats(null);
106
170
  expect(stats).toBeNull();
107
171
  });
108
- it('falls back to session-env directory counting when stats-cache.json missing', async () => {
109
- mockExistsPaths([
110
- '/mock-home/.claude',
111
- '/mock-home/.claude/session-env',
112
- ]);
113
- vi.mocked(readdirSync).mockReturnValue(['session-a', 'session-b', 'session-c']);
114
- vi.mocked(statSync).mockImplementation((p) => {
115
- const name = p.split('/').pop();
116
- const mtimes = {
117
- 'session-a': Date.now() - 1000,
118
- 'session-b': Date.now() - 2000,
119
- 'session-c': Date.now() - 3000,
120
- };
121
- return { mtimeMs: mtimes[name] ?? 0 };
172
+ it('skips malformed JSONL lines without crashing', async () => {
173
+ mockExistsPaths([CLAUDE_DIR, PROJECTS_DIR]);
174
+ vi.mocked(readdirSync).mockImplementation((p) => {
175
+ if (p === PROJECTS_DIR)
176
+ return ['cwd'];
177
+ if (p === `${PROJECTS_DIR}/cwd`)
178
+ return ['s.jsonl'];
179
+ return [];
122
180
  });
181
+ vi.mocked(statSync).mockReturnValue({ mtimeMs: 2_000_000_000_000 });
182
+ vi.mocked(readFileSync).mockReturnValue([
183
+ 'not json at all',
184
+ '{"type":"user","timestamp":"2026-04-13T22:00:00.000Z","message":{"role":"user","content":"ok"}}',
185
+ '{{{ broken',
186
+ '{"type":"assistant","timestamp":"2026-04-13T22:00:05.000Z","message":{"role":"assistant","content":[]}}',
187
+ '',
188
+ ].join('\n'));
123
189
  const stats = await adapter.readUsageStats(null);
124
190
  expect(stats).not.toBeNull();
125
- expect(stats.sessionCount).toBe(3);
126
- expect(stats.messageCount).toBe(0);
127
- expect(stats.hasNewActivity).toBe(true);
191
+ expect(stats.messageCount).toBe(2);
192
+ expect(stats.sessionCount).toBe(1);
128
193
  });
129
194
  });
130
195
  describe('ClaudeCodeAdapter.readVersion', () => {