@cachly-dev/mcp-server 0.10.26 → 0.10.40

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 (76) hide show
  1. package/.env.test.example +23 -0
  2. package/.github/ISSUE_TEMPLATE/bug_report.md +50 -0
  3. package/.github/ISSUE_TEMPLATE/config.yml +8 -0
  4. package/.github/ISSUE_TEMPLATE/feature_request.md +25 -0
  5. package/.github/workflows/publish.yml +72 -0
  6. package/CHANGELOG.md +252 -0
  7. package/LAUNCH_TEXTS.md +182 -0
  8. package/LICENSE +202 -0
  9. package/README.md +142 -112
  10. package/dist/__tests__/auth.test.d.ts +1 -0
  11. package/dist/__tests__/auth.test.js +107 -0
  12. package/dist/__tests__/auth.test.js.map +1 -0
  13. package/dist/__tests__/e2e/api-auth.test.d.ts +7 -0
  14. package/dist/__tests__/e2e/api-auth.test.js +162 -0
  15. package/dist/__tests__/e2e/api-auth.test.js.map +1 -0
  16. package/dist/__tests__/e2e/api-health.test.d.ts +7 -0
  17. package/dist/__tests__/e2e/api-health.test.js +95 -0
  18. package/dist/__tests__/e2e/api-health.test.js.map +1 -0
  19. package/dist/__tests__/e2e/cli.test.d.ts +10 -0
  20. package/dist/__tests__/e2e/cli.test.js +204 -0
  21. package/dist/__tests__/e2e/cli.test.js.map +1 -0
  22. package/dist/__tests__/e2e/config.d.ts +35 -0
  23. package/dist/__tests__/e2e/config.js +53 -0
  24. package/dist/__tests__/e2e/config.js.map +1 -0
  25. package/dist/__tests__/e2e/funnel.test.d.ts +13 -0
  26. package/dist/__tests__/e2e/funnel.test.js +90 -0
  27. package/dist/__tests__/e2e/funnel.test.js.map +1 -0
  28. package/dist/__tests__/e2e/mcp-tools.test.d.ts +7 -0
  29. package/dist/__tests__/e2e/mcp-tools.test.js +129 -0
  30. package/dist/__tests__/e2e/mcp-tools.test.js.map +1 -0
  31. package/dist/__tests__/e2e/provisioning.test.d.ts +15 -0
  32. package/dist/__tests__/e2e/provisioning.test.js +123 -0
  33. package/dist/__tests__/e2e/provisioning.test.js.map +1 -0
  34. package/dist/handlers/brain.js +119 -82
  35. package/dist/handlers/brain.js.map +1 -1
  36. package/dist/handlers/fedbrain.js +93 -44
  37. package/dist/handlers/fedbrain.js.map +1 -1
  38. package/dist/handlers/roadmap.js +8 -2
  39. package/dist/handlers/roadmap.js.map +1 -1
  40. package/dist/handlers/syndicate.js +15 -7
  41. package/dist/handlers/syndicate.js.map +1 -1
  42. package/dist/handlers/team.js +62 -50
  43. package/dist/handlers/team.js.map +1 -1
  44. package/dist/index.js +1264 -234
  45. package/dist/index.js.map +1 -1
  46. package/dist/tools.d.ts +3 -54
  47. package/dist/tools.js +8 -62
  48. package/dist/tools.js.map +1 -1
  49. package/eslint.config.js +16 -0
  50. package/glama.json +36 -0
  51. package/llms.txt +155 -0
  52. package/package.json +38 -14
  53. package/scripts/e2e-run.sh +160 -0
  54. package/scripts/postinstall.js +12 -12
  55. package/server.json +3 -9
  56. package/smithery.yaml +15 -8
  57. package/src/__tests__/auth.test.ts +147 -0
  58. package/src/__tests__/e2e/api-auth.test.ts +182 -0
  59. package/src/__tests__/e2e/api-health.test.ts +103 -0
  60. package/src/__tests__/e2e/cli.test.ts +228 -0
  61. package/src/__tests__/e2e/config.ts +53 -0
  62. package/src/__tests__/e2e/funnel.test.ts +99 -0
  63. package/src/__tests__/e2e/mcp-tools.test.ts +191 -0
  64. package/src/__tests__/e2e/provisioning.test.ts +128 -0
  65. package/src/handlers/brain.ts +118 -78
  66. package/src/handlers/fedbrain.ts +88 -38
  67. package/src/handlers/roadmap.ts +7 -2
  68. package/src/handlers/syndicate.ts +13 -7
  69. package/src/handlers/team.ts +57 -33
  70. package/src/index.ts +1312 -257
  71. package/src/tools.ts +8 -66
  72. package/vitest.config.ts +12 -0
  73. package/dist/__tests__/brain-predict-failures.test.d.ts +0 -17
  74. package/dist/__tests__/brain-predict-failures.test.js +0 -339
  75. package/dist/__tests__/brain-predict-failures.test.js.map +0 -1
  76. package/src/__tests__/brain-predict-failures.test.ts +0 -430
@@ -0,0 +1,228 @@
1
+ /**
2
+ * E2E: CLI command smoke tests
3
+ *
4
+ * Spawns the actual CLI binary and verifies output + exit codes.
5
+ * Uses the built dist/ — run `npm run build` first.
6
+ *
7
+ * Requires: E2E_JWT, E2E_INSTANCE_ID (for health/badge/share)
8
+ * Run: npm run build && npx vitest run src/__tests__/e2e/cli.test.ts
9
+ */
10
+
11
+ import { describe, it, expect } from 'vitest';
12
+ import { spawnSync } from 'node:child_process';
13
+ import { join } from 'node:path';
14
+ import { cfg } from './config.js';
15
+
16
+ const BIN = join(import.meta.dirname, '../../../../dist/index.js');
17
+ const TIMEOUT_MS = 30_000;
18
+
19
+ function run(
20
+ args: string[],
21
+ env: Record<string, string> = {},
22
+ timeoutMs = TIMEOUT_MS,
23
+ ): { stdout: string; stderr: string; code: number | null } {
24
+ const result = spawnSync(process.execPath, [BIN, ...args], {
25
+ env: {
26
+ ...process.env,
27
+ CACHLY_JWT: cfg.jwt,
28
+ CACHLY_BRAIN_INSTANCE_ID: cfg.instanceId,
29
+ CACHLY_API_URL: cfg.apiUrl,
30
+ ...env,
31
+ },
32
+ timeout: timeoutMs,
33
+ encoding: 'utf8',
34
+ });
35
+ return {
36
+ stdout: result.stdout ?? '',
37
+ stderr: result.stderr ?? '',
38
+ code: result.status,
39
+ };
40
+ }
41
+
42
+ describe('cachly (no args) — help output', () => {
43
+ it('exits 0', () => {
44
+ const { code } = run([]);
45
+ expect(code).toBe(0);
46
+ });
47
+
48
+ it('prints cachly branding', () => {
49
+ const { stdout } = run([]);
50
+ expect(stdout).toMatch(/cachly/i);
51
+ });
52
+
53
+ it('lists setup command', () => {
54
+ const { stdout } = run([]);
55
+ expect(stdout).toContain('setup');
56
+ });
57
+
58
+ it('lists demo command', () => {
59
+ const { stdout } = run([]);
60
+ expect(stdout).toContain('demo');
61
+ });
62
+
63
+ it('mentions 1–5 minutes (no false "30 seconds" promise)', () => {
64
+ const { stdout } = run([]);
65
+ // Must NOT contain "30 seconds" — we corrected this in v0.10.19+
66
+ expect(stdout).not.toContain('30 seconds');
67
+ expect(stdout).not.toMatch(/\b30s\b/);
68
+ });
69
+
70
+ it('mentions free forever', () => {
71
+ const { stdout } = run([]);
72
+ expect(stdout.toLowerCase()).toMatch(/free|kostenlos/);
73
+ });
74
+ });
75
+
76
+ describe('cachly upgrade', () => {
77
+ it('exits 0', () => {
78
+ const { code } = run(['upgrade']);
79
+ expect(code).toBe(0);
80
+ });
81
+
82
+ it('prints current version', () => {
83
+ const { stdout } = run(['upgrade']);
84
+ expect(stdout).toMatch(/\d+\.\d+\.\d+/);
85
+ });
86
+
87
+ it('version string is valid semver', () => {
88
+ const { stdout } = run(['upgrade']);
89
+ const match = stdout.match(/(\d+\.\d+\.\d+)/);
90
+ expect(match).not.toBeNull();
91
+ const parts = match![1].split('.').map(Number);
92
+ expect(parts).toHaveLength(3);
93
+ parts.forEach((p) => expect(Number.isInteger(p)).toBe(true));
94
+ });
95
+
96
+ it('does not crash on npm registry timeout (graceful error)', () => {
97
+ const { code } = run(['upgrade'], { CACHLY_API_URL: 'http://127.0.0.1:1' });
98
+ // Should exit 0 or 1 — never crash with unhandled exception
99
+ expect([0, 1]).toContain(code);
100
+ });
101
+ });
102
+
103
+ describe('cachly demo', () => {
104
+ it('exits 0 even without credentials', () => {
105
+ const { code } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
106
+ expect(code).toBe(0);
107
+ });
108
+
109
+ it('prints Brain Preview header', () => {
110
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
111
+ expect(stdout).toMatch(/brain|preview|cachly/i);
112
+ });
113
+
114
+ it('prints setup command at the end', () => {
115
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
116
+ expect(stdout).toContain('setup');
117
+ });
118
+
119
+ it('does not crash with invalid git repo (fallback gracefully)', () => {
120
+ const { code } = run(['demo'], {
121
+ CACHLY_JWT: '',
122
+ CACHLY_BRAIN_INSTANCE_ID: '',
123
+ }, 15_000);
124
+ expect([0, 1]).toContain(code); // never 2+ (unhandled crash)
125
+ });
126
+
127
+ it('shows Brain Level (valid level name)', () => {
128
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
129
+ // Demo must show a valid brain level — Apprentice for new projects is expected
130
+ expect(stdout).toMatch(/Apprentice|Explorer|Expert|Architect|Oracle/);
131
+ });
132
+
133
+ it('shows 1–5 minutes in the CTA (no "30 seconds")', () => {
134
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
135
+ expect(stdout).toContain('1–5 minutes');
136
+ expect(stdout).not.toContain('30 seconds');
137
+ });
138
+
139
+ it('shows "never repeat" instead of "remember" for bug fixes', () => {
140
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
141
+ // Copy should say "never repeat" not "remember" — old wording was weaker
142
+ if (stdout.includes('Bug fixes')) {
143
+ expect(stdout).toMatch(/never repeat/i);
144
+ }
145
+ });
146
+ });
147
+
148
+ describe('cachly health', () => {
149
+ it('exits 0 with valid credentials', () => {
150
+ if (!cfg.jwt || !cfg.instanceId) return;
151
+ const { code } = run(['health']);
152
+ expect(code).toBe(0);
153
+ });
154
+
155
+ it('prints API status', () => {
156
+ if (!cfg.jwt || !cfg.instanceId) return;
157
+ const { stdout } = run(['health']);
158
+ expect(stdout.toLowerCase()).toMatch(/api|status|ok|connected/);
159
+ });
160
+
161
+ it('prints editor detection results', () => {
162
+ if (!cfg.jwt || !cfg.instanceId) return;
163
+ const { stdout } = run(['health']);
164
+ expect(stdout.toLowerCase()).toMatch(/editor|claude|cursor|copilot|windsurf/);
165
+ });
166
+
167
+ it('exits non-zero without JWT', () => {
168
+ const { code, stdout } = run(['health'], { CACHLY_JWT: '' });
169
+ // Either exits non-zero, or prints an error message
170
+ const hasError = code !== 0 || stdout.toLowerCase().includes('not set') || stdout.toLowerCase().includes('sign in');
171
+ expect(hasError).toBe(true);
172
+ });
173
+ });
174
+
175
+ describe('cachly badge', () => {
176
+ it('exits 0 with valid instance', () => {
177
+ if (!cfg.jwt || !cfg.instanceId) return;
178
+ const { code } = run(['badge']);
179
+ expect(code).toBe(0);
180
+ });
181
+
182
+ it('outputs a markdown badge snippet', () => {
183
+ if (!cfg.jwt || !cfg.instanceId) return;
184
+ const { stdout } = run(['badge']);
185
+ expect(stdout).toMatch(/\[!\[.*cachly.*\]\(.*\)\]\(.*\)/i);
186
+ });
187
+
188
+ it('badge URL points to api.cachly.dev', () => {
189
+ if (!cfg.jwt || !cfg.instanceId) return;
190
+ const { stdout } = run(['badge']);
191
+ expect(stdout).toContain('api.cachly.dev');
192
+ });
193
+ });
194
+
195
+ describe('cachly share', () => {
196
+ it('exits 0 with valid credentials', () => {
197
+ if (!cfg.jwt || !cfg.instanceId) return;
198
+ const { code } = run(['share']);
199
+ expect(code).toBe(0);
200
+ });
201
+
202
+ it('output contains UTM share URL', () => {
203
+ if (!cfg.jwt || !cfg.instanceId) return;
204
+ const { stdout } = run(['share']);
205
+ expect(stdout).toContain('utm_source=x');
206
+ });
207
+
208
+ it('output contains tweet text', () => {
209
+ if (!cfg.jwt || !cfg.instanceId) return;
210
+ const { stdout } = run(['share']);
211
+ expect(stdout.toLowerCase()).toMatch(/tweet|x\.com|twitter/i);
212
+ });
213
+ });
214
+
215
+ describe('cachly invite', () => {
216
+ it('exits 0 and prints invite link', () => {
217
+ if (!cfg.jwt || !cfg.instanceId) return;
218
+ const { code, stdout } = run(['invite']);
219
+ expect(code).toBe(0);
220
+ expect(stdout).toMatch(/invite|join|cachly\.dev/i);
221
+ });
222
+
223
+ it('does NOT mention 30 seconds (1-5 minutes only)', () => {
224
+ if (!cfg.jwt || !cfg.instanceId) return;
225
+ const { stdout } = run(['invite']);
226
+ expect(stdout).not.toContain('30 seconds');
227
+ });
228
+ });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * E2E test configuration — read from environment variables.
3
+ *
4
+ * Required for full e2e run:
5
+ * E2E_API_URL Base URL of the API server (default: https://api.cachly.dev)
6
+ * E2E_JWT Valid Keycloak JWT for a test user
7
+ * E2E_INSTANCE_ID ID of a pre-provisioned (active) Brain instance
8
+ * E2E_API_KEY Redis password for the test instance
9
+ * E2E_REDIS_HOST Redis host for the test instance
10
+ * E2E_REDIS_PORT Redis port (default: 6380)
11
+ * E2E_REDIS_TLS "true" if TLS is required (default: true)
12
+ *
13
+ * Optional:
14
+ * E2E_SKIP_SLOW "true" to skip provisioning + device-flow tests
15
+ */
16
+
17
+ export const cfg = {
18
+ apiUrl: process.env.E2E_API_URL ?? 'https://api.cachly.dev',
19
+ jwt: process.env.E2E_JWT ?? '',
20
+ instanceId: process.env.E2E_INSTANCE_ID ?? '',
21
+ apiKey: process.env.E2E_API_KEY ?? '',
22
+ redisHost: process.env.E2E_REDIS_HOST ?? '',
23
+ redisPort: Number(process.env.E2E_REDIS_PORT ?? '6380'),
24
+ redisTls: (process.env.E2E_REDIS_TLS ?? 'true') !== 'false',
25
+ skipSlow: process.env.E2E_SKIP_SLOW === 'true',
26
+ };
27
+
28
+ export function requireAuth() {
29
+ if (!cfg.jwt) throw new Error('E2E_JWT is required — run: export E2E_JWT=<your-token>');
30
+ if (!cfg.instanceId) throw new Error('E2E_INSTANCE_ID is required');
31
+ }
32
+
33
+ export function requireRedis() {
34
+ requireAuth();
35
+ if (!cfg.apiKey) throw new Error('E2E_API_KEY is required');
36
+ if (!cfg.redisHost) throw new Error('E2E_REDIS_HOST is required');
37
+ }
38
+
39
+ export async function apiGet(path: string, jwt = cfg.jwt) {
40
+ const res = await fetch(`${cfg.apiUrl}${path}`, {
41
+ headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
42
+ });
43
+ return { status: res.status, body: await res.json().catch(() => null) };
44
+ }
45
+
46
+ export async function apiPost(path: string, body: unknown, jwt = cfg.jwt) {
47
+ const res = await fetch(`${cfg.apiUrl}${path}`, {
48
+ method: 'POST',
49
+ headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
50
+ body: JSON.stringify(body),
51
+ });
52
+ return { status: res.status, body: await res.json().catch(() => null) };
53
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * E2E: Activation funnel telemetry
3
+ *
4
+ * Verifies that every funnel event:
5
+ * setup_started → device_flow_started → device_flow_completed →
6
+ * first_call_success → onboarding_completed
7
+ *
8
+ * is accepted by the API and (after Docker redeploy) persisted to mcp_events.
9
+ *
10
+ * Requires: E2E_JWT, E2E_INSTANCE_ID
11
+ * Run: npx vitest run src/__tests__/e2e/funnel.test.ts
12
+ */
13
+
14
+ import { describe, it, expect, beforeAll } from 'vitest';
15
+ import { cfg, requireAuth, apiGet } from './config.js';
16
+
17
+ beforeAll(() => requireAuth());
18
+
19
+ const FUNNEL_EVENTS = [
20
+ 'setup_started',
21
+ 'device_flow_started',
22
+ 'device_flow_completed',
23
+ 'auto_provision_started',
24
+ 'first_call_success',
25
+ 'onboarding_completed',
26
+ ] as const;
27
+
28
+ async function postTelemetry(event: string, extra: Record<string, unknown> = {}) {
29
+ return fetch(`${cfg.apiUrl}/api/v1/telemetry/mcp`, {
30
+ method: 'POST',
31
+ headers: { 'Content-Type': 'application/json' },
32
+ body: JSON.stringify({
33
+ event,
34
+ version: '0.10.24',
35
+ editor: 'claude',
36
+ source: 'e2e',
37
+ jwt: cfg.jwt,
38
+ instance_id: cfg.instanceId,
39
+ ...extra,
40
+ }),
41
+ });
42
+ }
43
+
44
+ describe('Funnel event acceptance', () => {
45
+ for (const event of FUNNEL_EVENTS) {
46
+ it(`POST ${event} returns 2xx`, async () => {
47
+ const res = await postTelemetry(event);
48
+ expect(res.status).toBeGreaterThanOrEqual(200);
49
+ expect(res.status).toBeLessThan(300);
50
+ });
51
+ }
52
+
53
+ it('unknown event is accepted (API is permissive)', async () => {
54
+ const res = await postTelemetry('e2e_unknown_event_xyz');
55
+ expect(res.status).toBeGreaterThanOrEqual(200);
56
+ expect(res.status).toBeLessThan(300);
57
+ });
58
+
59
+ it('event with no jwt is still accepted', async () => {
60
+ const res = await fetch(`${cfg.apiUrl}/api/v1/telemetry/mcp`, {
61
+ method: 'POST',
62
+ headers: { 'Content-Type': 'application/json' },
63
+ body: JSON.stringify({ event: 'setup_started', version: '0.10.24', editor: 'cursor', source: 'mcp' }),
64
+ });
65
+ expect(res.status).toBeGreaterThanOrEqual(200);
66
+ expect(res.status).toBeLessThan(300);
67
+ });
68
+ });
69
+
70
+ describe('first_call_success attribution', () => {
71
+ it('fires with tool and instance_id fields', async () => {
72
+ const res = await postTelemetry('first_call_success', {
73
+ tool: 'brain_recall',
74
+ instance_id: cfg.instanceId,
75
+ });
76
+ expect(res.status).toBeGreaterThanOrEqual(200);
77
+ expect(res.status).toBeLessThan(300);
78
+ });
79
+
80
+ it('fires for different tools', async () => {
81
+ for (const tool of ['brain_store', 'session_start', 'causal_trace']) {
82
+ const res = await postTelemetry('first_call_success', { tool, instance_id: cfg.instanceId });
83
+ expect(res.status).toBeGreaterThanOrEqual(200);
84
+ expect(res.status).toBeLessThan(300);
85
+ }
86
+ });
87
+ });
88
+
89
+ describe('Funnel stats endpoint (post-deploy only)', () => {
90
+ it('daily summary telemetry query is reachable', async () => {
91
+ // This verifies the mcp_events table exists after Docker redeploy.
92
+ // Hits /api/v1/admin/funnel if it exists, otherwise checks telemetry endpoint.
93
+ const { status } = await apiGet('/api/v1/admin/funnel');
94
+ // 200 = table exists and endpoint works
95
+ // 404 = endpoint not exposed (acceptable — internal only via watchdog)
96
+ // 401/403 = auth required (also acceptable)
97
+ expect([200, 401, 403, 404]).toContain(status);
98
+ });
99
+ });
@@ -0,0 +1,191 @@
1
+ /**
2
+ * E2E: MCP tool calls via live Redis connection
3
+ *
4
+ * Requires: E2E_JWT, E2E_INSTANCE_ID, E2E_API_KEY, E2E_REDIS_HOST
5
+ * Run: npx vitest run src/__tests__/e2e/mcp-tools.test.ts
6
+ */
7
+
8
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
9
+ import { Redis } from 'ioredis';
10
+ import { cfg, requireRedis } from './config.js';
11
+
12
+ import { handleBrainTool } from '../../handlers/brain.js';
13
+ import { handleContextTool } from '../../handlers/context.js';
14
+
15
+ let redis: Redis;
16
+
17
+ function getConn(_id: string): Promise<Redis> {
18
+ return Promise.resolve(redis);
19
+ }
20
+
21
+ // ApiFetch matches the generic signature the handlers expect
22
+ async function apiFetch<T>(path: string, opts?: RequestInit): Promise<T> {
23
+ const res = await fetch(`${cfg.apiUrl}${path}`, {
24
+ ...opts,
25
+ headers: {
26
+ Authorization: `Bearer ${cfg.jwt}`,
27
+ 'Content-Type': 'application/json',
28
+ ...(opts?.headers as Record<string, string> ?? {}),
29
+ },
30
+ });
31
+ return res.json() as Promise<T>;
32
+ }
33
+
34
+ beforeAll(async () => {
35
+ requireRedis();
36
+ redis = new Redis({
37
+ host: cfg.redisHost,
38
+ port: cfg.redisPort,
39
+ password: cfg.apiKey,
40
+ tls: cfg.redisTls ? {} : undefined,
41
+ lazyConnect: true,
42
+ connectTimeout: 8000,
43
+ });
44
+ await redis.connect();
45
+ expect(await redis.ping()).toBe('PONG');
46
+ });
47
+
48
+ afterAll(async () => {
49
+ await redis.quit();
50
+ });
51
+
52
+ describe('Redis connectivity', () => {
53
+ it('PING returns PONG', async () => {
54
+ expect(await redis.ping()).toBe('PONG');
55
+ });
56
+
57
+ it('SET / GET round-trip works', async () => {
58
+ const key = `e2e:probe:${Date.now()}`;
59
+ await redis.set(key, 'ok', 'EX', 60);
60
+ expect(await redis.get(key)).toBe('ok');
61
+ await redis.del(key);
62
+ });
63
+ });
64
+
65
+ describe('session_start', () => {
66
+ it('returns a non-empty briefing string', async () => {
67
+ // session_start is handled by handleBrainTool, not handleContextTool
68
+ const result = await handleBrainTool(
69
+ 'session_start',
70
+ { instance_id: cfg.instanceId, focus: 'e2e-test' },
71
+ getConn,
72
+ apiFetch,
73
+ );
74
+ expect(typeof result === 'string' || result === null).toBe(true);
75
+ if (result !== null) expect(result.length).toBeGreaterThan(0);
76
+ });
77
+ });
78
+
79
+ describe('brain_store + brain_recall', () => {
80
+ const marker = `E2E-lesson-${Date.now()}`;
81
+
82
+ it('brain_store returns without error', async () => {
83
+ const result = await handleBrainTool(
84
+ 'brain_store',
85
+ {
86
+ instance_id: cfg.instanceId,
87
+ lesson: `${marker}: Redis race condition fixed with WAIT command`,
88
+ tags: ['e2e', 'redis', 'race-condition'],
89
+ severity: 'info',
90
+ },
91
+ getConn,
92
+ apiFetch,
93
+ );
94
+ // Returns a string (confirmation message) or null — never throws
95
+ expect(result === null || typeof result === 'string').toBe(true);
96
+ });
97
+
98
+ it('brain_recall finds the stored lesson', async () => {
99
+ await new Promise((r) => setTimeout(r, 400));
100
+ const result = await handleBrainTool(
101
+ 'brain_recall',
102
+ {
103
+ instance_id: cfg.instanceId,
104
+ query: marker,
105
+ limit: 5,
106
+ },
107
+ getConn,
108
+ apiFetch,
109
+ );
110
+ // Result is a formatted string with lessons, or null if empty
111
+ if (result !== null) {
112
+ expect(result).toContain(marker.split(':')[0]);
113
+ }
114
+ });
115
+
116
+ it('brain_recall handles unknown query gracefully (no throw)', async () => {
117
+ const result = await handleBrainTool(
118
+ 'brain_recall',
119
+ { instance_id: cfg.instanceId, query: 'xyzzy-no-match-e2e-99887766', limit: 3 },
120
+ getConn,
121
+ apiFetch,
122
+ );
123
+ expect(result === null || typeof result === 'string').toBe(true);
124
+ });
125
+ });
126
+
127
+ describe('brain_from_git (smoke)', () => {
128
+ it('responds without throwing', async () => {
129
+ const result = await handleBrainTool(
130
+ 'brain_from_git',
131
+ { instance_id: cfg.instanceId, max_commits: 5 },
132
+ getConn,
133
+ apiFetch,
134
+ );
135
+ expect(result === null || typeof result === 'string').toBe(true);
136
+ });
137
+ });
138
+
139
+ describe('causal_trace', () => {
140
+ it('returns a trace string without throwing', async () => {
141
+ const result = await handleBrainTool(
142
+ 'causal_trace',
143
+ { instance_id: cfg.instanceId, problem: 'auth breaks after restart', depth: 2 },
144
+ getConn,
145
+ apiFetch,
146
+ );
147
+ expect(result === null || typeof result === 'string').toBe(true);
148
+ });
149
+ });
150
+
151
+ describe('brain_predict', () => {
152
+ it('returns a prediction string without throwing', async () => {
153
+ const result = await handleBrainTool(
154
+ 'brain_predict',
155
+ { instance_id: cfg.instanceId, target: 'deploy' },
156
+ getConn,
157
+ apiFetch,
158
+ );
159
+ expect(result === null || typeof result === 'string').toBe(true);
160
+ });
161
+ });
162
+
163
+ describe('session_end', () => {
164
+ it('persists session summary without throwing', async () => {
165
+ const result = await handleContextTool(
166
+ 'session_end',
167
+ {
168
+ instance_id: cfg.instanceId,
169
+ summary: 'E2E test session completed.',
170
+ lessons: ['brain_recall round-trip verified', 'causal_trace responded correctly'],
171
+ },
172
+ getConn,
173
+ apiFetch,
174
+ );
175
+ expect(result === null || typeof result === 'string').toBe(true);
176
+ });
177
+ });
178
+
179
+ describe('brain_health', () => {
180
+ it('returns a health string containing a positive indicator', async () => {
181
+ const result = await handleBrainTool(
182
+ 'brain_health',
183
+ { instance_id: cfg.instanceId },
184
+ getConn,
185
+ apiFetch,
186
+ );
187
+ if (result !== null) {
188
+ expect(result.toLowerCase()).toMatch(/ok|healthy|active|ping|pong|connected/);
189
+ }
190
+ });
191
+ });
@@ -0,0 +1,128 @@
1
+ /**
2
+ * E2E: Provisioning flow
3
+ *
4
+ * Tests the full instance lifecycle:
5
+ * create → poll until active (or timeout) → connect → delete
6
+ *
7
+ * ⚠️ This test creates a real instance and WILL be billed if not deleted.
8
+ * It always cleans up in afterAll, even on failure.
9
+ *
10
+ * Skipped if E2E_SKIP_SLOW=true.
11
+ *
12
+ * Requires: E2E_JWT
13
+ * Run: npx vitest run src/__tests__/e2e/provisioning.test.ts --reporter=verbose
14
+ */
15
+
16
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
17
+ import { cfg, requireAuth, apiGet, apiPost } from './config.js';
18
+
19
+ beforeAll(() => {
20
+ requireAuth();
21
+ if (cfg.skipSlow) {
22
+ console.log('Skipping provisioning tests (E2E_SKIP_SLOW=true)');
23
+ }
24
+ });
25
+
26
+ let createdInstanceId: string | null = null;
27
+
28
+ afterAll(async () => {
29
+ if (!createdInstanceId) return;
30
+ try {
31
+ const res = await fetch(`${cfg.apiUrl}/api/v1/instances/${createdInstanceId}`, {
32
+ method: 'DELETE',
33
+ headers: { Authorization: `Bearer ${cfg.jwt}` },
34
+ });
35
+ console.log(`Cleanup: deleted instance ${createdInstanceId} → ${res.status}`);
36
+ } catch (e) {
37
+ console.warn(`Cleanup failed for ${createdInstanceId}:`, e);
38
+ }
39
+ });
40
+
41
+ describe('Instance provisioning lifecycle', () => {
42
+ it.skipIf(cfg.skipSlow)('POST /api/v1/instances creates a new free instance', async () => {
43
+ const { status, body } = await apiPost('/api/v1/instances', {
44
+ name: `e2e-test-${Date.now()}`,
45
+ tier: 'free',
46
+ });
47
+ expect([200, 201]).toContain(status);
48
+ const inst = body as Record<string, unknown>;
49
+ expect(typeof inst.id).toBe('string');
50
+ expect(inst.status).toMatch(/^(provisioning|active)$/);
51
+ createdInstanceId = inst.id as string;
52
+ });
53
+
54
+ it.skipIf(cfg.skipSlow)('instance status transitions from provisioning → active within 5 min', async () => {
55
+ if (!createdInstanceId) return;
56
+
57
+ const maxWaitMs = 5 * 60 * 1000; // 5 minutes
58
+ const pollMs = 10_000; // poll every 10 seconds
59
+ const start = Date.now();
60
+ let status = 'provisioning';
61
+
62
+ while (Date.now() - start < maxWaitMs) {
63
+ await new Promise((r) => setTimeout(r, pollMs));
64
+ const { body } = await apiGet(`/api/v1/instances/${createdInstanceId}`);
65
+ status = (body as Record<string, unknown>).status as string;
66
+ console.log(` [${Math.round((Date.now() - start) / 1000)}s] status: ${status}`);
67
+ if (status === 'active') break;
68
+ if (status === 'failed') break;
69
+ }
70
+
71
+ expect(status).toBe('active');
72
+ }, 6 * 60 * 1000); // vitest timeout: 6 min
73
+
74
+ it.skipIf(cfg.skipSlow)('active instance returns valid connection details', async () => {
75
+ if (!createdInstanceId) return;
76
+ const { status, body } = await apiGet(`/api/v1/instances/${createdInstanceId}/connection`);
77
+ expect(status).toBe(200);
78
+ const conn = body as Record<string, unknown>;
79
+ expect(typeof conn.host).toBe('string');
80
+ expect(Number(conn.port)).toBeGreaterThan(0);
81
+ expect(typeof conn.password).toBe('string');
82
+ });
83
+
84
+ it.skipIf(cfg.skipSlow)('can PING the provisioned Redis', async () => {
85
+ if (!createdInstanceId) return;
86
+ const { body } = await apiGet(`/api/v1/instances/${createdInstanceId}/connection`);
87
+ const conn = body as Record<string, unknown>;
88
+
89
+ const { Redis: RedisClass } = await import('ioredis');
90
+ const r = new RedisClass({
91
+ host: conn.host as string,
92
+ port: Number(conn.port),
93
+ password: conn.password as string,
94
+ tls: cfg.redisTls ? {} : undefined,
95
+ connectTimeout: 8000,
96
+ lazyConnect: true,
97
+ });
98
+ try {
99
+ await r.connect();
100
+ expect(await r.ping()).toBe('PONG');
101
+ } finally {
102
+ await r.quit();
103
+ }
104
+ });
105
+ });
106
+
107
+ describe('Provisioning status — failed instance handling', () => {
108
+ it('failed status returns meaningful error (not 500) from connection endpoint', async () => {
109
+ // We use a known-bad UUID to simulate a missing/failed instance
110
+ const { status } = await apiGet('/api/v1/instances/00000000-0000-0000-0000-000000000000/connection');
111
+ // Should be a client error (4xx), never a server error (5xx)
112
+ expect(status).toBeGreaterThanOrEqual(400);
113
+ expect(status).toBeLessThan(500);
114
+ });
115
+ });
116
+
117
+ describe('Auto-provision via /instances/auto', () => {
118
+ it.skipIf(cfg.skipSlow)('POST /api/v1/instances/auto returns instance id', async () => {
119
+ const { status, body } = await apiPost('/api/v1/instances/auto', {});
120
+ // 200 = existing instance returned
121
+ // 201 = new instance created
122
+ // 409 = already has an instance (also fine)
123
+ expect([200, 201, 409]).toContain(status);
124
+ if (status !== 409) {
125
+ expect(typeof (body as Record<string, unknown>).id).toBe('string');
126
+ }
127
+ });
128
+ });