@cachly-dev/mcp-server 0.10.14 → 0.10.16

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 (44) hide show
  1. package/.github/ISSUE_TEMPLATE/bug_report.md +50 -0
  2. package/.github/ISSUE_TEMPLATE/config.yml +8 -0
  3. package/.github/ISSUE_TEMPLATE/feature_request.md +25 -0
  4. package/.github/workflows/publish.yml +72 -0
  5. package/CHANGELOG.md +59 -0
  6. package/LAUNCH_TEXTS.md +182 -0
  7. package/LICENSE +202 -0
  8. package/README.md +136 -112
  9. package/dist/__tests__/auth.test.d.ts +1 -0
  10. package/dist/__tests__/auth.test.js +107 -0
  11. package/dist/__tests__/auth.test.js.map +1 -0
  12. package/dist/handlers/brain.js +7 -67
  13. package/dist/handlers/brain.js.map +1 -1
  14. package/dist/handlers/fedbrain.js +93 -44
  15. package/dist/handlers/fedbrain.js.map +1 -1
  16. package/dist/handlers/roadmap.js +8 -2
  17. package/dist/handlers/roadmap.js.map +1 -1
  18. package/dist/handlers/syndicate.js +15 -7
  19. package/dist/handlers/syndicate.js.map +1 -1
  20. package/dist/handlers/team.js +62 -50
  21. package/dist/handlers/team.js.map +1 -1
  22. package/dist/index.js +724 -95
  23. package/dist/index.js.map +1 -1
  24. package/dist/tools.d.ts +3 -54
  25. package/dist/tools.js +8 -62
  26. package/dist/tools.js.map +1 -1
  27. package/glama.json +36 -0
  28. package/llms.txt +155 -0
  29. package/package.json +29 -13
  30. package/scripts/postinstall.js +12 -12
  31. package/server.json +3 -9
  32. package/smithery.yaml +15 -8
  33. package/src/__tests__/auth.test.ts +147 -0
  34. package/src/handlers/brain.ts +7 -64
  35. package/src/handlers/fedbrain.ts +88 -38
  36. package/src/handlers/roadmap.ts +7 -2
  37. package/src/handlers/syndicate.ts +13 -7
  38. package/src/handlers/team.ts +57 -33
  39. package/src/index.ts +755 -108
  40. package/src/tools.ts +8 -66
  41. package/dist/__tests__/brain-predict-failures.test.d.ts +0 -17
  42. package/dist/__tests__/brain-predict-failures.test.js +0 -339
  43. package/dist/__tests__/brain-predict-failures.test.js.map +0 -1
  44. package/src/__tests__/brain-predict-failures.test.ts +0 -430
package/src/index.ts CHANGED
@@ -53,7 +53,7 @@ import { Redis } from 'ioredis';
53
53
  const API_URL = process.env.CACHLY_API_URL ?? 'https://api.cachly.dev';
54
54
  let JWT = process.env.CACHLY_JWT ?? '';
55
55
  const EMBED_MODEL = process.env.CACHLY_EMBED_MODEL ?? '';
56
- const CURRENT_VERSION = '0.10.10';
56
+ const CURRENT_VERSION = '0.10.16';
57
57
 
58
58
  // ── Default Instance Resolution (for Smithery & single-credential setups) ────
59
59
  // When CACHLY_BRAIN_INSTANCE_ID is set, tools can omit the instance_id parameter.
@@ -635,33 +635,7 @@ const server = new Server(
635
635
  { capabilities: { tools: {} } }
636
636
  );
637
637
 
638
- server.setRequestHandler(ListToolsRequestSchema, async () => {
639
- if (!JWT) {
640
- // No credentials — inject sign-up CTA into session_start description
641
- const tools = TOOLS.map(t => {
642
- if (t.name !== 'session_start') return t;
643
- return {
644
- ...t,
645
- description:
646
- `⚡ FREE AI BRAIN — sign up once at https://cachly.dev/sign-up (no credit card) ` +
647
- `then run: npx @cachly-dev/mcp-server@latest setup\n\n` + t.description,
648
- };
649
- });
650
- return { tools };
651
- }
652
-
653
- // ── Auto-start session on connection (fire and forget) ────────────────────
654
- // When the AI reads the tools list, it has just connected. Proactively start
655
- // the Brain session in the background so by the time the first tool call
656
- // arrives, session context is already loaded and ready to inject.
657
- if (!_autoSessionStarted && !_autoSessionStarting) {
658
- void resolveDefaultInstanceId().then(instanceId => {
659
- if (instanceId) void autoStartSession(instanceId).catch(() => undefined);
660
- }).catch(() => undefined);
661
- }
662
-
663
- return { tools: TOOLS };
664
- });
638
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
665
639
 
666
640
  // ── Auto-session management ───────────────────────────────────────────────────
667
641
  // Transparently starts a Brain session on the first tool call of a process
@@ -670,91 +644,59 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
670
644
 
671
645
  let _autoSessionInstanceId: string | null = null;
672
646
  let _autoSessionStarted = false;
673
- let _autoSessionStarting: Promise<string | null> | null = null; // guard against double-start race
647
+ let _autoSessionStarting: Promise<void> | null = null; // guard against double-start race
674
648
  let _autoSessionToolCount = 0;
675
- let _autoSessionContext: string | null = null; // result of session_start, injected into first tool response
676
- let _autoSessionContextInjected = false; // only inject once
677
649
 
678
650
  // ── brain_from_git concurrency limiter ────────────────────────────────────────
679
651
  // Spawning many `git log` subprocesses in parallel can fork-bomb the host.
680
652
  // This simple semaphore caps concurrent brain_from_git calls to 10 per process.
681
- async function autoStartSession(instanceId: string): Promise<string | null> {
682
- if (_autoSessionStarted) return null;
653
+ async function autoStartSession(instanceId: string): Promise<void> {
654
+ if (_autoSessionStarted) return;
683
655
  // If another call already started the session, await it instead of double-starting.
684
- if (_autoSessionStarting) { return _autoSessionStarting; }
685
- _autoSessionStarting = (async (): Promise<string | null> => {
656
+ if (_autoSessionStarting) { await _autoSessionStarting; return; }
657
+ _autoSessionStarting = (async () => {
686
658
  _autoSessionStarted = true;
687
659
  _autoSessionInstanceId = instanceId;
688
- let sessionResult: string | null = null;
689
660
  try {
690
- // Auto-detect git context for a meaningful session focus
691
- let focus = 'auto (MCP session)';
692
- try {
693
- const { execSync } = await import('node:child_process');
694
- const branch = execSync('git rev-parse --abbrev-ref HEAD',
695
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }
696
- ).trim();
697
- const lastMsg = execSync('git log -1 --pretty=%s',
698
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }
699
- ).trim();
700
- if (branch && branch !== 'HEAD') {
701
- focus = lastMsg ? `${branch}: ${lastMsg.slice(0, 80)}` : `branch: ${branch}`;
702
- }
703
- } catch { /* git not available in this workspace */ }
704
- sessionResult = await handleTool('session_start', { instance_id: instanceId, focus });
705
- _autoSessionContext = sessionResult;
661
+ await handleTool('session_start', { instance_id: instanceId, focus: 'auto (MCP session)' });
706
662
  } catch { /* non-fatal — session tracking is a best-effort feature */ } finally {
707
663
  _autoSessionStarting = null;
708
664
  }
709
-
710
- // Auto-index the project if it hasn't been indexed in the last 24h.
711
- // This is the main lever for growing token savings: more indexed code →
712
- // more semantic cache hits → fewer LLM calls for repeated questions.
713
- if (process.env.CACHLY_AUTO_INDEX !== 'false') {
714
- try {
715
- const redis = await getConnection(instanceId);
716
- const lastIndexed = await redis.get(`cachly:index:last_indexed:${instanceId}`);
717
- const staleMs = 24 * 60 * 60 * 1000;
718
- const isStale = !lastIndexed || (Date.now() - parseInt(lastIndexed, 10)) > staleMs;
719
- if (isStale) {
720
- // Mark as indexing now to prevent concurrent re-runs.
721
- await redis.set(`cachly:index:last_indexed:${instanceId}`, String(Date.now()), 'EX', 90000);
722
- // Run in background — don't block the first tool call.
723
- handleTool('index_project', {
724
- instance_id: instanceId,
725
- dir: process.cwd(),
726
- max_files: 150,
727
- ttl: 86400 * 7, // cache for 7 days
728
- namespace: 'cachly:sem:code',
729
- }).catch(() => undefined);
730
- }
731
- } catch { /* never block the session on indexing errors */ }
732
- }
733
-
734
- return sessionResult;
735
665
  })();
736
- return _autoSessionStarting;
666
+ await _autoSessionStarting;
667
+
668
+ // Auto-index the project if it hasn't been indexed in the last 24h.
669
+ // This is the main lever for growing token savings: more indexed code →
670
+ // more semantic cache hits → fewer LLM calls for repeated questions.
671
+ if (process.env.CACHLY_AUTO_INDEX !== 'false') {
672
+ try {
673
+ const redis = await getConnection(instanceId);
674
+ const lastIndexed = await redis.get(`cachly:index:last_indexed:${instanceId}`);
675
+ const staleMs = 24 * 60 * 60 * 1000;
676
+ const isStale = !lastIndexed || (Date.now() - parseInt(lastIndexed, 10)) > staleMs;
677
+ if (isStale) {
678
+ // Mark as indexing now to prevent concurrent re-runs.
679
+ await redis.set(`cachly:index:last_indexed:${instanceId}`, String(Date.now()), 'EX', 90000);
680
+ // Run in background — don't block the first tool call.
681
+ handleTool('index_project', {
682
+ instance_id: instanceId,
683
+ dir: process.cwd(),
684
+ max_files: 150,
685
+ ttl: 86400 * 7, // cache for 7 days
686
+ namespace: 'cachly:sem:code',
687
+ }).catch(() => undefined);
688
+ }
689
+ } catch { /* never block the session on indexing errors */ }
690
+ }
737
691
  }
738
692
 
739
693
  async function autoEndSession(): Promise<void> {
740
694
  if (!_autoSessionStarted || !_autoSessionInstanceId) return;
741
695
  _autoSessionStarted = false;
742
696
  try {
743
- // Try to derive a meaningful summary from git
744
- let summary = `Auto-ended after ${_autoSessionToolCount} tool call(s).`;
745
- try {
746
- const { execSync } = await import('node:child_process');
747
- const branch = execSync('git rev-parse --abbrev-ref HEAD',
748
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }
749
- ).trim();
750
- const lastMsg = execSync('git log -1 --pretty=%s',
751
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }
752
- ).trim();
753
- if (lastMsg) summary = `${branch ? `[${branch}] ` : ''}${lastMsg} · ${_autoSessionToolCount} tool calls`;
754
- } catch { /* git unavailable */ }
755
697
  await handleTool('session_end', {
756
698
  instance_id: _autoSessionInstanceId,
757
- summary,
699
+ summary: `Auto-ended after ${_autoSessionToolCount} tool call(s). Session was started automatically.`,
758
700
  files_changed: [],
759
701
  lessons_learned: 0,
760
702
  });
@@ -764,7 +706,7 @@ async function autoEndSession(): Promise<void> {
764
706
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
765
707
  const { name, arguments: args } = request.params;
766
708
 
767
- // Auto-start brain session if not yet started (fallback: ListTools already fired this).
709
+ // Auto-start brain session on first tool call that has an instance_id.
768
710
  // Skip session management tools to avoid recursion.
769
711
  const sessionTools = new Set(['session_start', 'session_end', 'auto_learn_session']);
770
712
  if (!sessionTools.has(name) && !_autoSessionStarted && !_autoSessionStarting) {
@@ -782,18 +724,6 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
782
724
 
783
725
  try {
784
726
  const text = await handleTool(name, (args ?? {}) as Record<string, unknown>);
785
-
786
- // ── Inject session context into the FIRST tool response ─────────────────
787
- // This is the key: the AI sees the previous session summary, handoff tasks,
788
- // and recent lessons automatically — without needing to call session_start.
789
- // Only injected once per process (on the very first tool call).
790
- if (!_autoSessionContextInjected && _autoSessionContext && !sessionTools.has(name)) {
791
- _autoSessionContextInjected = true;
792
- const ctx = _autoSessionContext;
793
- _autoSessionContext = null; // free memory
794
- return { content: [{ type: 'text', text: `${ctx}\n\n---\n\n${text}` }] };
795
- }
796
-
797
727
  return { content: [{ type: 'text', text }] };
798
728
  } catch (err) {
799
729
  if (err instanceof McpError) throw err;
@@ -945,6 +875,565 @@ async function writeClaudeMd(projectDir: string, instanceId: string): Promise<'w
945
875
  return 'written';
946
876
  }
947
877
 
878
+
879
+
880
+ // ── CLI: cachly digest ────────────────────────────────────────────────────────
881
+ // Usage: npx @cachly-dev/mcp-server@latest digest
882
+ // Weekly brain summary — what your AI learned this week. Shareable output.
883
+
884
+ if (process.argv[2] === 'digest') {
885
+ const apiKey = process.env.CACHLY_JWT ?? '';
886
+ const instanceId = process.env.CACHLY_BRAIN_INSTANCE_ID ?? '';
887
+
888
+ if (!apiKey || !instanceId) {
889
+ console.log('\n⚠️ CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.');
890
+ console.log(' Run: npx @cachly-dev/mcp-server@latest setup\n');
891
+ process.exit(1);
892
+ }
893
+
894
+ process.stdout.write('\n🧠 Fetching your weekly Brain digest...\n\n');
895
+
896
+ try {
897
+ // Fetch current stats
898
+ const statsRes = await fetch(`${API_URL}/api/v1/instances/${instanceId}/brain/stats`, {
899
+ headers: { Authorization: `Bearer ${apiKey}` },
900
+ signal: AbortSignal.timeout(8000),
901
+ });
902
+ if (!statsRes.ok) throw new Error(`stats HTTP ${statsRes.status}`);
903
+ const stats = await statsRes.json() as {
904
+ lesson_count?: number; context_count?: number; quality_score?: number;
905
+ total_recall_count?: number; top_lessons?: Array<{ topic: string; recall_count: number; what_worked: string }>;
906
+ team_authors?: string[];
907
+ };
908
+
909
+ const lessons = stats.lesson_count ?? 0;
910
+ const recalls = stats.total_recall_count ?? 0;
911
+ const score = Math.round((stats.quality_score ?? 0) * 100);
912
+ const topLessons = (stats.top_lessons ?? []).slice(0, 5);
913
+ const teamAuthors = stats.team_authors ?? [];
914
+ const tokensSaved = recalls * 1200;
915
+ const costSaved = (tokensSaved * 0.000003).toFixed(2);
916
+
917
+ const level = lessons < 10 ? 'Junior Dev 🔧' : lessons < 30 ? 'Mid Dev ⚡' :
918
+ lessons < 60 ? 'Senior Dev 🧠' : lessons < 100 ? 'Staff Eng 🚀' : 'Principal Eng 🏆';
919
+
920
+ const now = new Date();
921
+ const weekStart = new Date(now); weekStart.setDate(now.getDate() - 7);
922
+ const fmt = (d: Date) => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
923
+
924
+ console.log('┌─────────────────────────────────────────────────────────────┐');
925
+ console.log(`│ \x1b[1m🧠 Brain Weekly Digest\x1b[0m \x1b[90m${fmt(weekStart)} – ${fmt(now)}\x1b[0m │`);
926
+ console.log('├─────────────────────────────────────────────────────────────┤');
927
+ console.log(`│ Total lessons : \x1b[33m${String(lessons).padEnd(8)}\x1b[0m Brain level : \x1b[32m${level.padEnd(18)}\x1b[0m│`);
928
+ console.log(`│ Total recalls : \x1b[36m${String(recalls).padEnd(8)}\x1b[0m Quality score: \x1b[32m${String(score).padEnd(3)}%\x1b[0m │`);
929
+ console.log(`│ Tokens saved : \x1b[32m${String(Math.round(tokensSaved / 1000) + 'K').padEnd(8)}\x1b[0m Cost saved : \x1b[32m$${costSaved.padEnd(20)}\x1b[0m│`);
930
+
931
+ if (teamAuthors.length > 0) {
932
+ console.log('├─────────────────────────────────────────────────────────────┤');
933
+ console.log(`│ \x1b[36m👥 Team contributors:\x1b[0m ${teamAuthors.slice(0, 5).join(', ').slice(0, 42).padEnd(42)} │`);
934
+ }
935
+
936
+ if (topLessons.length > 0) {
937
+ console.log('├─────────────────────────────────────────────────────────────┤');
938
+ console.log('│ \x1b[33m🔥 Most recalled lessons this week:\x1b[0m │');
939
+ for (const l of topLessons) {
940
+ const line = `${l.topic}: ${l.what_worked}`.slice(0, 57);
941
+ console.log(`│ \x1b[90m• ${line.padEnd(58)}\x1b[0m│`);
942
+ }
943
+ }
944
+
945
+ console.log('├─────────────────────────────────────────────────────────────┤');
946
+ console.log('│ \x1b[32m📋 Share this digest:\x1b[0m │');
947
+ console.log('│ \x1b[90m npx @cachly-dev/mcp-server@latest share\x1b[0m │');
948
+ console.log('│ \x1b[90m Add more: npx @cachly-dev/mcp-server@latest invite\x1b[0m │');
949
+ console.log('└─────────────────────────────────────────────────────────────┘');
950
+ console.log('');
951
+
952
+ // Pro tip for cron
953
+ console.log(' \x1b[2m💡 Automate: add to crontab for a weekly team email\x1b[0m');
954
+ console.log(' \x1b[2m 0 9 * * 1 npx @cachly-dev/mcp-server@latest digest\x1b[0m');
955
+ console.log('');
956
+ } catch (e) {
957
+ console.log(`\n❌ Could not fetch digest: ${(e as Error).message}\n`);
958
+ process.exit(1);
959
+ }
960
+ process.exit(0);
961
+ }
962
+
963
+ // ── CLI: cachly invite ────────────────────────────────────────────────────────
964
+ // Usage: npx @cachly-dev/mcp-server@latest invite [email]
965
+ // Invites a teammate to share your Brain. Fastest referral loop.
966
+
967
+ if (process.argv[2] === 'invite') {
968
+ const { createInterface } = await import('node:readline');
969
+ const apiKey = process.env.CACHLY_JWT ?? '';
970
+
971
+ if (!apiKey) {
972
+ console.log('\n⚠️ CACHLY_JWT must be set.');
973
+ console.log(' Run: npx @cachly-dev/mcp-server@latest setup\n');
974
+ process.exit(1);
975
+ }
976
+
977
+ let email = process.argv[3] ?? '';
978
+
979
+ if (!email) {
980
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
981
+ email = await new Promise<string>((resolve) => {
982
+ rl.question('\n 📬 Teammate email to invite: ', (ans) => { rl.close(); resolve(ans.trim()); });
983
+ });
984
+ }
985
+
986
+ if (!email || !email.includes('@')) {
987
+ console.log('\n❌ Invalid email address.\n');
988
+ process.exit(1);
989
+ }
990
+
991
+ console.log(`\n ⏳ Inviting ${email}...`);
992
+
993
+ try {
994
+ const res = await fetch(`${API_URL}/api/v1/team/invite`, {
995
+ method: 'POST',
996
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
997
+ body: JSON.stringify({ email, role: 'member', source: 'cli-invite' }),
998
+ signal: AbortSignal.timeout(8000),
999
+ });
1000
+
1001
+ if (res.ok) {
1002
+ console.log(`\n ✅ Invite sent to \x1b[32m${email}\x1b[0m`);
1003
+ console.log(` They'll get a link to join your Brain — one click, 30 seconds.\n`);
1004
+ console.log(` 💡 Once they join, your AI assistants share lessons automatically.\n`);
1005
+ } else if (res.status === 409) {
1006
+ console.log(`\n ✓ ${email} is already a team member.\n`);
1007
+ } else {
1008
+ const body = await res.json().catch(() => ({})) as { error?: string };
1009
+ console.log(`\n ❌ Invite failed: ${body.error ?? `HTTP ${res.status}`}\n`);
1010
+ process.exit(1);
1011
+ }
1012
+ } catch (e) {
1013
+ console.log(`\n ❌ Network error: ${(e as Error).message}\n`);
1014
+ process.exit(1);
1015
+ }
1016
+ process.exit(0);
1017
+ }
1018
+
1019
+ // ── CLI: cachly join <token> ──────────────────────────────────────────────────
1020
+ // Usage: npx @cachly-dev/mcp-server@latest join <token>
1021
+ // Accepts a Brain invite link — writes the shared instance ID into all
1022
+ // detected editor MCP configs and the global ~/.claude/mcp.json.
1023
+ // No account needed if CACHLY_JWT is already set; otherwise prompts for auth.
1024
+
1025
+ if (process.argv[2] === 'join') {
1026
+ const { writeFile: wfJ, readFile: rfJ, mkdir: mkJ } = await import('node:fs/promises');
1027
+ const { existsSync: exJ } = await import('node:fs');
1028
+ const { resolve: resJ, dirname: dirJ } = await import('node:path');
1029
+ const { homedir } = await import('node:os');
1030
+ const { createInterface: ciJ } = await import('node:readline');
1031
+
1032
+ const token = process.argv[3] ?? '';
1033
+ if (!token) {
1034
+ console.log('\n❌ Usage: npx @cachly-dev/mcp-server@latest join <token>\n');
1035
+ console.log(' Get a token from a teammate: npx @cachly-dev/mcp-server@latest invite\n');
1036
+ process.exit(1);
1037
+ }
1038
+
1039
+ console.log('\n⏳ Looking up invite...');
1040
+
1041
+ // ── Step 1: Fetch invite info (public, no auth) ───────────────────────────
1042
+ let inviteInfo: { instance_id: string; instance_name: string; tier: string; expires_at: string; label?: string };
1043
+ try {
1044
+ const res = await fetch(`${API_URL}/api/invite/${token}`, { signal: AbortSignal.timeout(8000) });
1045
+ if (res.status === 404) { console.log('\n❌ Invite not found — the link may be invalid.\n'); process.exit(1); }
1046
+ if (res.status === 410) { console.log('\n❌ This invite link has expired (7-day limit).\n'); process.exit(1); }
1047
+ if (!res.ok) { console.log(`\n❌ Could not fetch invite: HTTP ${res.status}\n`); process.exit(1); }
1048
+ inviteInfo = await res.json() as typeof inviteInfo;
1049
+ } catch (e) {
1050
+ console.log(`\n❌ Network error: ${(e as Error).message}\n`);
1051
+ process.exit(1);
1052
+ }
1053
+
1054
+ const { instance_id, instance_name, tier, label } = inviteInfo;
1055
+ const expires = new Date(inviteInfo.expires_at).toLocaleDateString();
1056
+
1057
+ console.log('');
1058
+ console.log(' \x1b[35m╔══════════════════════════════════════════════════════╗\x1b[0m');
1059
+ console.log(' \x1b[35m║\x1b[0m \x1b[1m🧠 Brain Invite\x1b[0m \x1b[35m║\x1b[0m');
1060
+ console.log(' \x1b[35m╚══════════════════════════════════════════════════════╝\x1b[0m');
1061
+ console.log('');
1062
+ console.log(` Brain : \x1b[1m${instance_name}\x1b[0m`);
1063
+ console.log(` Tier : ${tier}`);
1064
+ if (label) console.log(` Note : ${label}`);
1065
+ console.log(` Expires : ${expires}`);
1066
+ console.log('');
1067
+
1068
+ // ── Step 2: Confirm ───────────────────────────────────────────────────────
1069
+ const rlJ = ciJ({ input: process.stdin, output: process.stdout });
1070
+ const confirmJ = await new Promise<string>((resolve) => {
1071
+ rlJ.question(' Join this Brain? [Y/n] ', (a) => { rlJ.close(); resolve(a.trim().toLowerCase() || 'y'); });
1072
+ });
1073
+ if (confirmJ !== 'y' && confirmJ !== 'yes') {
1074
+ console.log('\n Cancelled.\n');
1075
+ process.exit(0);
1076
+ }
1077
+
1078
+ // ── Step 3: Ensure JWT ────────────────────────────────────────────────────
1079
+ let joinJwt = JWT;
1080
+ if (!joinJwt) {
1081
+ console.log('\n No API key found — starting sign-in (10 seconds)...\n');
1082
+ try {
1083
+ const dcRes = await fetch(`${API_URL}/api/v1/auth/device/code`, {
1084
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
1085
+ body: JSON.stringify({ client_id: 'cachly-mcp-cli' }),
1086
+ signal: AbortSignal.timeout(10000),
1087
+ });
1088
+ if (dcRes.ok) {
1089
+ const dc = await dcRes.json() as { verification_uri: string; user_code: string; device_code: string; interval: number };
1090
+ console.log(` 👉 Open: \x1b[36m${dc.verification_uri}\x1b[0m`);
1091
+ console.log(` Code: \x1b[1m${dc.user_code}\x1b[0m\n`);
1092
+ // Poll for token
1093
+ const pollInterval = (dc.interval ?? 5) * 1000;
1094
+ for (let i = 0; i < 24; i++) {
1095
+ await new Promise(r => setTimeout(r, pollInterval));
1096
+ try {
1097
+ const tokRes = await fetch(`${API_URL}/api/v1/auth/device/token`, {
1098
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
1099
+ body: JSON.stringify({ device_code: dc.device_code, client_id: 'cachly-mcp-cli' }),
1100
+ signal: AbortSignal.timeout(8000),
1101
+ });
1102
+ if (tokRes.ok) {
1103
+ const tok = await tokRes.json() as { access_token?: string };
1104
+ if (tok.access_token) { joinJwt = tok.access_token; break; }
1105
+ }
1106
+ } catch { /* polling — keep going */ }
1107
+ }
1108
+ if (!joinJwt) { console.log('\n❌ Sign-in timed out. Run the command again.\n'); process.exit(1); }
1109
+ console.log(' ✅ Signed in!\n');
1110
+ }
1111
+ } catch (e) {
1112
+ console.log(`\n ⚠️ Could not start sign-in: ${(e as Error).message}`);
1113
+ console.log(` Set CACHLY_JWT manually from https://cachly.dev/setup-ai\n`);
1114
+ process.exit(1);
1115
+ }
1116
+ }
1117
+
1118
+ // ── Step 4: Write instance ID into all editor MCP configs ────────────────
1119
+ const cwd = process.cwd();
1120
+ const home = homedir();
1121
+
1122
+ const editorFiles: Array<{ label: string; path: string; global?: boolean }> = [
1123
+ { label: '.mcp.json (Claude Code project)', path: resJ(cwd, '.mcp.json') },
1124
+ { label: '.cursor/mcp.json', path: resJ(cwd, '.cursor', 'mcp.json') },
1125
+ { label: '.windsurf/mcp.json', path: resJ(cwd, '.windsurf', 'mcp.json') },
1126
+ { label: '.vscode/mcp.json (Copilot/Cline)', path: resJ(cwd, '.vscode', 'mcp.json') },
1127
+ { label: '~/.claude/mcp.json (global)', path: resJ(home, '.claude', 'mcp.json'), global: true },
1128
+ ];
1129
+
1130
+ let written = 0;
1131
+ for (const { label: eLabel, path: ePath, global: isGlobal } of editorFiles) {
1132
+ // Only write project configs if the directory exists (or global)
1133
+ const dir = dirJ(ePath);
1134
+ if (!isGlobal && !exJ(dir) && !exJ(ePath)) continue;
1135
+ try {
1136
+ await mkJ(dir, { recursive: true });
1137
+ let cfg: Record<string, unknown> = {};
1138
+ if (exJ(ePath)) {
1139
+ try { cfg = JSON.parse(await rfJ(ePath, 'utf-8')) as Record<string, unknown>; } catch { /* corrupt — overwrite */ }
1140
+ }
1141
+ // Update or create the cachly entry with the shared instance ID
1142
+ const servers = (cfg['mcpServers'] ?? {}) as Record<string, unknown>;
1143
+ const existing = (servers['cachly'] ?? {}) as Record<string, unknown>;
1144
+ const env = (existing['env'] ?? {}) as Record<string, string>;
1145
+ env['CACHLY_BRAIN_INSTANCE_ID'] = instance_id;
1146
+ if (joinJwt && !env['CACHLY_JWT']) env['CACHLY_JWT'] = joinJwt;
1147
+ env['CACHLY_API_URL'] ??= 'https://api.cachly.dev';
1148
+ servers['cachly'] = { ...existing, command: 'npx', args: ['-y', '@cachly-dev/mcp-server@latest'], env };
1149
+ cfg['mcpServers'] = servers;
1150
+ await wfJ(ePath, JSON.stringify(cfg, null, 2), 'utf-8');
1151
+ console.log(` ✅ ${eLabel}`);
1152
+ written++;
1153
+ } catch { /* skip — not all editors are installed */ }
1154
+ }
1155
+
1156
+ console.log('');
1157
+ if (written === 0) {
1158
+ console.log(' ⚠️ No editor configs found — run `cachly setup` first.\n');
1159
+ } else {
1160
+ console.log(` 🧠 You're now sharing Brain: \x1b[1m${instance_name}\x1b[0m`);
1161
+ console.log(' Restart your editor — your AI arrives pre-briefed from the team Brain.\n');
1162
+ console.log(' 📛 Add the badge to your README:');
1163
+ console.log(` npx @cachly-dev/mcp-server@latest badge\n`);
1164
+ }
1165
+ process.exit(0);
1166
+ }
1167
+
1168
+ // ── CLI: cachly demo ──────────────────────────────────────────────────────────
1169
+ // Usage: npx @cachly-dev/mcp-server@latest demo
1170
+ // Zero-signup. Reads local git history and shows what the AI Brain would know.
1171
+ // The fastest path from "what is this?" to "I need this".
1172
+
1173
+ if (process.argv[2] === 'demo') {
1174
+ const { execSync } = await import('node:child_process');
1175
+ const { existsSync } = await import('node:fs');
1176
+ const { resolve } = await import('node:path');
1177
+ const cwd = process.cwd();
1178
+
1179
+ console.log('\n\x1b[35m🧠 cachly Brain — Live Demo\x1b[0m');
1180
+ console.log('\x1b[90mNo account needed. Reading your git history...\x1b[0m\n');
1181
+
1182
+ // Verify git repo
1183
+ if (!existsSync(resolve(cwd, '.git'))) {
1184
+ console.log('⚠️ No git repository found here.');
1185
+ console.log(' Run this command inside a project directory with git history.\n');
1186
+ console.log(' Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo\n');
1187
+ process.exit(0);
1188
+ }
1189
+
1190
+ // Read git log
1191
+ let logOutput = '';
1192
+ try {
1193
+ logOutput = execSync(
1194
+ 'git log HEAD --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n 200',
1195
+ { cwd, encoding: 'utf-8', stdio: 'pipe' }
1196
+ );
1197
+ } catch {
1198
+ console.log('⚠️ Could not read git log. Make sure you have commits.\n');
1199
+ process.exit(0);
1200
+ }
1201
+
1202
+ const commits = logOutput.trim().split('\n').filter(Boolean).map(line => {
1203
+ const [sha, subject, date, author] = line.split('|||');
1204
+ return { sha: (sha ?? '').trim().slice(0, 8), subject: (subject ?? '').trim(), date: (date ?? '').trim(), author: (author ?? '').trim() };
1205
+ });
1206
+
1207
+ if (commits.length === 0) {
1208
+ console.log('⚠️ No commits found.\n');
1209
+ process.exit(0);
1210
+ }
1211
+
1212
+ // Classify commits (same logic as brain_from_git)
1213
+ const classify = (s: string) => {
1214
+ const t = s.toLowerCase();
1215
+ if (/\b(fix|fixed|bug|hotfix|patch|revert|resolve)\b/.test(t)) return 'fix';
1216
+ if (/\b(feat|feature|add|implement|new|introduce)\b/.test(t)) return 'feat';
1217
+ if (/\b(perf|optim|speed|cache|latency)\b/.test(t)) return 'perf';
1218
+ if (/\b(security|cve|auth|csrf|xss|inject|sanitize)\b/.test(t)) return 'security';
1219
+ if (/\b(deploy|ci|cd|docker|k8s|infra)\b/.test(t)) return 'deploy';
1220
+ if (/\b(refactor|clean|simplify|extract)\b/.test(t)) return 'refactor';
1221
+ return 'chore';
1222
+ };
1223
+
1224
+ // Count categories
1225
+ const cats = new Map<string, number>();
1226
+ const fixes: string[] = [];
1227
+ const feats: string[] = [];
1228
+ const security: string[] = [];
1229
+ const authors = new Set<string>();
1230
+
1231
+ for (const c of commits) {
1232
+ const cat = classify(c.subject);
1233
+ cats.set(cat, (cats.get(cat) ?? 0) + 1);
1234
+ if (cat === 'fix' && fixes.length < 5) fixes.push(c.subject.slice(0, 72));
1235
+ if (cat === 'feat' && feats.length < 5) feats.push(c.subject.slice(0, 72));
1236
+ if (cat === 'security' && security.length < 3) security.push(c.subject.slice(0, 72));
1237
+ if (c.author) authors.add(c.author.split(' ')[0]!);
1238
+ }
1239
+
1240
+ const totalLessons = commits.length - (cats.get('chore') ?? 0);
1241
+ const dateRange = `${commits[commits.length - 1]?.date ?? '?'} → ${commits[0]?.date ?? '?'}`;
1242
+
1243
+ // Display the demo
1244
+ process.stdout.write('\x1b[2K\r');
1245
+ console.log('┌─────────────────────────────────────────────────────────────┐');
1246
+ console.log('│ \x1b[1m🧠 Brain Preview — What your AI would know\x1b[0m │');
1247
+ console.log('├─────────────────────────────────────────────────────────────┤');
1248
+ console.log(`│ Commits analysed : \x1b[33m${String(commits.length).padEnd(6)}\x1b[0m Date range: \x1b[90m${dateRange.slice(0, 23).padEnd(23)}\x1b[0m │`);
1249
+ console.log(`│ Lessons extracted: \x1b[32m${String(totalLessons).padEnd(6)}\x1b[0m Contributors: \x1b[36m${String(authors.size).padEnd(20)}\x1b[0m│`);
1250
+ console.log('├─────────────────────────────────────────────────────────────┤');
1251
+
1252
+ // Category breakdown
1253
+ const sorted = [...cats.entries()].filter(([k]) => k !== 'chore').sort((a, b) => b[1] - a[1]);
1254
+ const bar = (n: number, max: number) => '█'.repeat(Math.round((n / max) * 20)).padEnd(20);
1255
+ const maxVal = Math.max(...sorted.map(([, v]) => v), 1);
1256
+ console.log('│ \x1b[90mCategory breakdown:\x1b[0m │');
1257
+ for (const [cat, count] of sorted) {
1258
+ const emoji = { fix: '🔧', feat: '✨', perf: '⚡', security: '🔒', deploy: '🚀', refactor: '🔄' }[cat] ?? '•';
1259
+ console.log(`│ ${emoji} \x1b[36m${cat.padEnd(10)}\x1b[0m \x1b[35m${bar(count, maxVal)}\x1b[0m \x1b[33m${String(count).padStart(3)}\x1b[0m │`);
1260
+ }
1261
+
1262
+ if (security.length > 0) {
1263
+ console.log('├─────────────────────────────────────────────────────────────┤');
1264
+ console.log('│ \x1b[31m🔒 Security fixes your AI would know:\x1b[0m │');
1265
+ for (const s of security) console.log(`│ \x1b[90m• ${s.slice(0, 58).padEnd(58)}\x1b[0m │`);
1266
+ }
1267
+
1268
+ if (fixes.length > 0) {
1269
+ console.log('├─────────────────────────────────────────────────────────────┤');
1270
+ console.log('│ \x1b[33m🔧 Bug fixes your AI would remember:\x1b[0m │');
1271
+ for (const f of fixes.slice(0, 4)) console.log(`│ \x1b[90m• ${f.slice(0, 58).padEnd(58)}\x1b[0m │`);
1272
+ }
1273
+
1274
+ if (feats.length > 0) {
1275
+ console.log('├─────────────────────────────────────────────────────────────┤');
1276
+ console.log('│ \x1b[32m✨ Features & decisions it would recall:\x1b[0m │');
1277
+ for (const f of feats.slice(0, 3)) console.log(`│ \x1b[90m• ${f.slice(0, 58).padEnd(58)}\x1b[0m │`);
1278
+ }
1279
+
1280
+ console.log('├─────────────────────────────────────────────────────────────┤');
1281
+ console.log('│ \x1b[32m💡 With cachly, your AI arrives pre-briefed every session.\x1b[0m │');
1282
+ console.log('│ \x1b[32m No more re-explaining. No more repeated mistakes.\x1b[0m │');
1283
+ console.log('└─────────────────────────────────────────────────────────────┘');
1284
+ console.log('');
1285
+ console.log(' \x1b[1mMake this permanent (free, 30 seconds):\x1b[0m');
1286
+ console.log(' \x1b[32m$ npx @cachly-dev/mcp-server@latest setup\x1b[0m');
1287
+ console.log('');
1288
+ console.log(' Works with: Claude Code · Cursor · Windsurf · Copilot · Cline · Zed');
1289
+ console.log(' Free forever · GDPR · German servers · No credit card');
1290
+ console.log('');
1291
+ process.exit(0);
1292
+ }
1293
+
1294
+ // ── CLI: cachly share ─────────────────────────────────────────────────────────
1295
+ // Usage: npx @cachly-dev/mcp-server@latest share
1296
+ // Generates a shareable ASCII card + tweet text with your Brain stats.
1297
+
1298
+ if (process.argv[2] === 'share') {
1299
+ const apiKey = process.env.CACHLY_JWT ?? '';
1300
+ const instanceId = process.env.CACHLY_BRAIN_INSTANCE_ID ?? '';
1301
+
1302
+ if (!apiKey || !instanceId) {
1303
+ console.log('\n⚠️ CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.');
1304
+ console.log(' Run: npx @cachly-dev/mcp-server@latest setup (takes 30 seconds)\n');
1305
+ process.exit(1);
1306
+ }
1307
+
1308
+ process.stdout.write('\n🧠 Fetching your Brain stats...\n');
1309
+
1310
+ try {
1311
+ const statsRes = await fetch(`${API_URL}/api/v1/instances/${instanceId}/brain/stats`, {
1312
+ headers: { Authorization: `Bearer ${apiKey}` },
1313
+ signal: AbortSignal.timeout(8000),
1314
+ });
1315
+
1316
+ if (!statsRes.ok) throw new Error(`HTTP ${statsRes.status}`);
1317
+ const stats = await statsRes.json() as {
1318
+ lesson_count?: number; context_count?: number;
1319
+ quality_score?: number; total_recall_count?: number;
1320
+ };
1321
+
1322
+ const lessons = stats.lesson_count ?? 0;
1323
+ const recalls = stats.total_recall_count ?? 0;
1324
+ const score = Math.round((stats.quality_score ?? 0) * 100);
1325
+ const tokensSaved = recalls * 1200;
1326
+ const costSaved = (tokensSaved * 0.000003).toFixed(2);
1327
+
1328
+ const level = lessons === 0 ? 'Intern 🌱' :
1329
+ lessons < 10 ? 'Junior Dev 🔧' :
1330
+ lessons < 30 ? 'Mid Dev ⚡' :
1331
+ lessons < 60 ? 'Senior Dev 🧠' :
1332
+ lessons < 100 ? 'Staff Eng 🚀' : 'Principal Eng 🏆';
1333
+
1334
+ console.log('');
1335
+ console.log('┌─────────────────────────────────────────────────────────────┐');
1336
+ console.log('│ 🧠 My AI Brain · powered by \x1b[35mcachly.dev\x1b[0m │');
1337
+ console.log('├─────────────────────────────────────────────────────────────┤');
1338
+ console.log(`│ Lessons stored : \x1b[33m${String(lessons).padEnd(8)}\x1b[0m Brain level: \x1b[32m${level.padEnd(18)}\x1b[0m│`);
1339
+ console.log(`│ Total recalls : \x1b[36m${String(recalls).padEnd(8)}\x1b[0m Quality score: \x1b[32m${String(score).padEnd(3)}%\x1b[0m │`);
1340
+ console.log(`│ Tokens saved : \x1b[32m${String((tokensSaved / 1000).toFixed(0) + 'K').padEnd(8)}\x1b[0m Cost saved: \x1b[32m$${costSaved.padEnd(20)}\x1b[0m│`);
1341
+ console.log('├─────────────────────────────────────────────────────────────┤');
1342
+ console.log('│ Works with: Claude Code · Cursor · Windsurf · Copilot │');
1343
+ console.log('│ Free · GDPR · German servers │');
1344
+ console.log('│ \x1b[35mnpx @cachly-dev/mcp-server@latest setup\x1b[0m │');
1345
+ console.log('└─────────────────────────────────────────────────────────────┘');
1346
+ console.log('');
1347
+
1348
+ // Tweet text
1349
+ const tweet = `🧠 My AI coding assistant now has persistent memory.\n\n${lessons} lessons stored · ${recalls} recalls · ${level}\n\nFix a bug once → AI remembers forever. Across Claude Code, Cursor, Windsurf, Copilot.\n\nnpx @cachly-dev/mcp-server@latest setup\n\n#AIMemory #ClaudeCode #Cursor #DeveloperTools`;
1350
+
1351
+ console.log(' \x1b[1m📋 Share on Twitter/X (copy this):\x1b[0m');
1352
+ console.log(' ─────────────────────────────────────');
1353
+ console.log(tweet.split('\n').map(l => ` ${l}`).join('\n'));
1354
+ console.log(' ─────────────────────────────────────');
1355
+ console.log('');
1356
+ console.log(' \x1b[2mPro tip: add a screenshot of your Brain panel for 3x more engagement\x1b[0m');
1357
+ console.log(' \x1b[2mAlso add a live badge to your README:\x1b[0m');
1358
+ console.log(` \x1b[90m npx @cachly-dev/mcp-server@latest badge\x1b[0m`);
1359
+ console.log('');
1360
+ } catch (e) {
1361
+ console.log(`\n❌ Could not fetch stats: ${(e as Error).message}\n`);
1362
+ process.exit(1);
1363
+ }
1364
+ process.exit(0);
1365
+ }
1366
+
1367
+ // ── CLI: cachly badge ─────────────────────────────────────────────────────────
1368
+ // Outputs the Markdown + HTML snippet for embedding a live Brain lesson-count
1369
+ // badge in any README or website. Badge SVG served by cachly API (public, no auth).
1370
+
1371
+ if (process.argv[2] === 'badge') {
1372
+ const instanceId = process.env.CACHLY_BRAIN_INSTANCE_ID ?? '';
1373
+
1374
+ if (!instanceId) {
1375
+ console.log('\n⚠️ CACHLY_BRAIN_INSTANCE_ID must be set.');
1376
+ console.log(' Run: npx @cachly-dev/mcp-server@latest setup (takes 30 seconds)\n');
1377
+ process.exit(1);
1378
+ }
1379
+
1380
+ const badgeUrl = `${API_URL}/api/v1/badge/${instanceId}`;
1381
+ const targetUrl = 'https://cachly.dev';
1382
+ const markdown = `[![cachly Brain](${badgeUrl})](${targetUrl})`;
1383
+ const htmlBadge = `<a href="${targetUrl}"><img src="${badgeUrl}" alt="cachly Brain" /></a>`;
1384
+
1385
+ console.log('');
1386
+ console.log('\x1b[35m ╔═══════════════════════════════════════════════════════╗\x1b[0m');
1387
+ console.log('\x1b[35m ║\x1b[0m \x1b[1m🧠 cachly Brain Badge\x1b[0m \x1b[35m║\x1b[0m');
1388
+ console.log('\x1b[35m ╚═══════════════════════════════════════════════════════╝\x1b[0m');
1389
+ console.log('');
1390
+ console.log(' Paste into your README.md:');
1391
+ console.log('');
1392
+ console.log(` \x1b[32m${markdown}\x1b[0m`);
1393
+ console.log('');
1394
+ console.log(' ─────────────────────────────────────────────────────');
1395
+ console.log(' Or paste into HTML:');
1396
+ console.log('');
1397
+ console.log(` \x1b[36m${htmlBadge}\x1b[0m`);
1398
+ console.log('');
1399
+ console.log(' ─────────────────────────────────────────────────────');
1400
+ console.log(' Badge URL (live, updates every hour):');
1401
+ console.log(` \x1b[90m${badgeUrl}\x1b[0m`);
1402
+ console.log('');
1403
+ console.log(' \x1b[2mThe badge shows your current lesson count — no auth required,');
1404
+ console.log(' safe to embed in public repos. Updates hourly.\x1b[0m');
1405
+ console.log('');
1406
+ process.exit(0);
1407
+ }
1408
+
1409
+ // ── CLI: no-args splash screen ────────────────────────────────────────────────
1410
+ // When run with no recognized subcommand, show a compelling pitch + help.
1411
+
1412
+ if (!process.argv[2] && process.stdout.isTTY) {
1413
+ console.log('');
1414
+ console.log('\x1b[35m ╔═══════════════════════════════════════════════════════╗\x1b[0m');
1415
+ console.log('\x1b[35m ║\x1b[0m \x1b[1m🧠 cachly — Persistent AI Memory for Developers\x1b[0m \x1b[35m║\x1b[0m');
1416
+ console.log('\x1b[35m ╚═══════════════════════════════════════════════════════╝\x1b[0m');
1417
+ console.log('');
1418
+ console.log(' Your AI forgets everything when a session ends.');
1419
+ console.log(' cachly gives it a brain that survives forever.');
1420
+ console.log('');
1421
+ console.log(' \x1b[1mCommands:\x1b[0m');
1422
+ console.log(' \x1b[32m npx @cachly-dev/mcp-server@latest demo\x1b[0m ← Start here (no account)');
1423
+ console.log(' \x1b[32m npx @cachly-dev/mcp-server@latest setup\x1b[0m ← Wire up your AI editors');
1424
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest health\x1b[0m ← Check everything works');
1425
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest digest\x1b[0m ← Weekly Brain summary');
1426
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest share\x1b[0m ← Share your Brain stats');
1427
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest badge\x1b[0m ← README badge for your Brain');
1428
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest invite\x1b[0m ← Invite a teammate');
1429
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest join <token>\x1b[0m ← Accept a Brain invite');
1430
+ console.log('');
1431
+ console.log(' \x1b[90mWorks with: Claude Code · Cursor · Windsurf · GitHub Copilot · Cline · Zed\x1b[0m');
1432
+ console.log(' \x1b[90mFree forever · GDPR · German servers · 89 MCP tools\x1b[0m');
1433
+ console.log('');
1434
+ process.exit(0);
1435
+ }
1436
+
948
1437
  // ── CLI: cachly init ──────────────────────────────────────────────────────────
949
1438
  // Usage: npx @cachly-dev/mcp-server init --instance-id <id> --api-key <key> [--editor claude|cursor|windsurf|copilot|continue] [--project-dir /path]
950
1439
 
@@ -1014,7 +1503,161 @@ if (process.argv[2] === 'init') {
1014
1503
  } catch { /* non-critical — git hook is a best-effort feature */ }
1015
1504
 
1016
1505
  console.log(`\n🧠 Cachly AI Brain configured for ${editor === 'claude' ? 'Claude Code' : editor}!`);
1017
- console.log(` Restart your editor — the \`cachly\` MCP tools will appear.\n`);
1506
+ console.log(` Restart your editor — the \`cachly\` MCP tools will appear.`);
1507
+ console.log(`\n 📛 Add a live badge to your README:`);
1508
+ console.log(` npx @cachly-dev/mcp-server@latest badge\n`);
1509
+ process.exit(0);
1510
+ }
1511
+
1512
+ // ── CLI: cachly health ────────────────────────────────────────────────────────
1513
+ // Usage: npx @cachly-dev/mcp-server@latest health
1514
+ // Checks: JWT valid, Brain API reachable, editor configs found, git hook present.
1515
+
1516
+ if (process.argv[2] === 'health') {
1517
+ const { existsSync } = await import('node:fs');
1518
+ const { readFile } = await import('node:fs/promises');
1519
+ const { resolve, join: pJoin } = await import('node:path');
1520
+
1521
+ const cwd = process.cwd();
1522
+ let passed = 0;
1523
+ let failed = 0;
1524
+
1525
+ const ok = (msg: string) => { console.log(` ✅ ${msg}`); passed++; };
1526
+ const warn = (msg: string) => { console.log(` ⚠️ ${msg}`); };
1527
+ const fail = (msg: string) => { console.log(` ❌ ${msg}`); failed++; };
1528
+
1529
+ console.log('\n🧠 cachly health check\n');
1530
+
1531
+ // ── 1. JWT token ────────────────────────────────────────────────────────────
1532
+ console.log('🔑 Auth token');
1533
+ const jwt = process.env.CACHLY_JWT ?? '';
1534
+ if (!jwt) {
1535
+ fail('CACHLY_JWT not set — run: npx @cachly-dev/mcp-server@latest setup');
1536
+ } else {
1537
+ try {
1538
+ const parts = jwt.split('.');
1539
+ if (parts.length !== 3) throw new Error('not a JWT');
1540
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf-8')) as {
1541
+ sub?: string; exp?: number;
1542
+ };
1543
+ const expMs = payload.exp ? payload.exp * 1000 : null;
1544
+ const minsLeft = expMs ? Math.floor((expMs - Date.now()) / 60_000) : null;
1545
+ if (expMs && expMs < Date.now()) {
1546
+ fail(`JWT expired ${Math.abs(minsLeft!)} minute(s) ago — get a new one: https://cachly.dev/setup-ai`);
1547
+ } else if (minsLeft !== null && minsLeft < 30) {
1548
+ warn(`JWT expires in ${minsLeft} minute(s) — refresh soon at https://cachly.dev/setup-ai`);
1549
+ } else {
1550
+ ok(`JWT valid${minsLeft !== null ? ` (expires in ${Math.floor(minsLeft / 60)}h ${minsLeft % 60}m)` : ''}`);
1551
+ }
1552
+ } catch {
1553
+ fail('CACHLY_JWT format invalid (expected JWT with 3 parts)');
1554
+ }
1555
+ }
1556
+
1557
+ // ── 2. Brain API reachability ───────────────────────────────────────────────
1558
+ console.log('\n🌐 Brain API');
1559
+ const apiUrl = process.env.CACHLY_API_URL ?? 'https://api.cachly.dev';
1560
+ try {
1561
+ const res = await fetch(`${apiUrl}/health`, { signal: AbortSignal.timeout(5000) });
1562
+ if (res.ok) {
1563
+ const body = await res.json() as { status?: string };
1564
+ ok(`${apiUrl} reachable (status: ${body.status ?? 'ok'})`);
1565
+ } else if (res.status === 401 || res.status === 403) {
1566
+ ok(`${apiUrl} reachable (auth required — expected)`);
1567
+ } else {
1568
+ fail(`${apiUrl}/health returned HTTP ${res.status}`);
1569
+ }
1570
+ } catch (e) {
1571
+ fail(`${apiUrl} unreachable — ${(e as Error).message}`);
1572
+ }
1573
+
1574
+ // ── 3. Brain instance ───────────────────────────────────────────────────────
1575
+ console.log('\n🧠 Brain instance');
1576
+ const instanceId = process.env.CACHLY_BRAIN_INSTANCE_ID ?? '';
1577
+ if (!instanceId) {
1578
+ warn('CACHLY_BRAIN_INSTANCE_ID not set — will auto-resolve on first tool call');
1579
+ } else if (jwt) {
1580
+ try {
1581
+ const instRes = await fetch(`${apiUrl}/api/v1/instances/${instanceId}`, {
1582
+ headers: { Authorization: `Bearer ${jwt}`, Accept: 'application/json' },
1583
+ signal: AbortSignal.timeout(5000),
1584
+ });
1585
+ if (instRes.ok) {
1586
+ const inst = await instRes.json() as { name?: string; status?: string };
1587
+ if (inst.status === 'running') {
1588
+ ok(`Instance "${inst.name}" (${instanceId.slice(0, 8)}…) is running`);
1589
+ } else {
1590
+ warn(`Instance "${inst.name}" status: ${inst.status}`);
1591
+ }
1592
+ } else {
1593
+ fail(`Instance ${instanceId.slice(0, 8)}… not found (HTTP ${instRes.status})`);
1594
+ }
1595
+ } catch (e) {
1596
+ fail(`Could not check instance — ${(e as Error).message}`);
1597
+ }
1598
+ }
1599
+
1600
+ // ── 4. Editor configs ───────────────────────────────────────────────────────
1601
+ console.log('\n🛠 Editor configs (project dir)');
1602
+ const editorConfigs: Array<{ editor: string; path: string }> = [
1603
+ { editor: 'Claude Code', path: '.mcp.json' },
1604
+ { editor: 'Cursor', path: '.cursor/mcp.json' },
1605
+ { editor: 'Windsurf', path: '.windsurf/mcp.json' },
1606
+ { editor: 'Copilot / Cline', path: '.vscode/mcp.json' },
1607
+ { editor: 'Zed', path: '.zed/settings.json' },
1608
+ { editor: 'Continue.dev', path: '.continue/config.json' },
1609
+ ];
1610
+ let configsFound = 0;
1611
+ for (const { editor, path } of editorConfigs) {
1612
+ const fullPath = resolve(cwd, path);
1613
+ if (existsSync(fullPath)) {
1614
+ try {
1615
+ const content = await readFile(fullPath, 'utf-8');
1616
+ const hasCachly = content.includes('@cachly-dev/mcp-server') || content.includes('cachly');
1617
+ if (hasCachly) {
1618
+ ok(`${editor}: ${path}`);
1619
+ configsFound++;
1620
+ } else {
1621
+ warn(`${editor}: ${path} exists but cachly not found inside`);
1622
+ }
1623
+ } catch {
1624
+ warn(`${editor}: ${path} exists but could not read`);
1625
+ }
1626
+ }
1627
+ }
1628
+ if (configsFound === 0) {
1629
+ fail('No editor MCP configs found — run: npx @cachly-dev/mcp-server@latest setup');
1630
+ }
1631
+
1632
+ // ── 5. Git hook ─────────────────────────────────────────────────────────────
1633
+ console.log('\n🪝 Git hook (ambient learning)');
1634
+ const hookPath = resolve(cwd, '.git', 'hooks', 'post-commit');
1635
+ if (!existsSync(resolve(cwd, '.git'))) {
1636
+ warn('Not in a git repository — skip');
1637
+ } else if (existsSync(hookPath)) {
1638
+ try {
1639
+ const hook = await readFile(hookPath, 'utf-8');
1640
+ if (hook.includes('cachly')) {
1641
+ ok('.git/hooks/post-commit (cachly CLS hook present)');
1642
+ } else {
1643
+ warn('.git/hooks/post-commit exists but cachly hook not found — run setup to add it');
1644
+ }
1645
+ } catch {
1646
+ warn('.git/hooks/post-commit exists but could not read');
1647
+ }
1648
+ } else {
1649
+ warn('.git/hooks/post-commit not found — run: npx @cachly-dev/mcp-server@latest setup');
1650
+ }
1651
+
1652
+ // ── Summary ─────────────────────────────────────────────────────────────────
1653
+ console.log(`\n${'─'.repeat(40)}`);
1654
+ if (failed === 0) {
1655
+ console.log(`✅ All checks passed (${passed} ok)\n`);
1656
+ } else {
1657
+ console.log(`❌ ${failed} check(s) failed, ${passed} passed\n`);
1658
+ console.log(`💡 Fix issues with: npx @cachly-dev/mcp-server@latest setup\n`);
1659
+ process.exit(1);
1660
+ }
1018
1661
  process.exit(0);
1019
1662
  }
1020
1663
 
@@ -1378,7 +2021,9 @@ if (process.argv[2] === 'setup') {
1378
2021
 
1379
2022
  console.log(`\n🧠 Done! Restart your editor — the \`cachly\` MCP tools will appear.`);
1380
2023
  console.log(` Your AI now has persistent memory across every session.\n`);
1381
- console.log(` Dashboard: https://cachly.dev/instances/${instance.id}\n`);
2024
+ console.log(` Dashboard: https://cachly.dev/instances/${instance.id}`);
2025
+ console.log(`\n 📛 Add a live badge to your README:`);
2026
+ console.log(` npx @cachly-dev/mcp-server@latest badge\n`);
1382
2027
 
1383
2028
  // ── Step 7: Email opt-in (non-blocking — at the very end) ────────────────
1384
2029
  if (!nonInteractive) {
@@ -1478,7 +2123,9 @@ if (process.argv[2] === 'index') {
1478
2123
 
1479
2124
  // Warn on stderr when credentials are missing so the user sees a clear
1480
2125
  // actionable message in their editor's MCP log instead of silent failures.
1481
- if (!JWT) {
2126
+ // Skip for CLI commands that intentionally run without credentials.
2127
+ const _cliNoAuthCommands = ['demo', 'share', 'health', 'setup', 'init', 'digest', 'invite', 'badge', 'join'];
2128
+ if (!JWT && !_cliNoAuthCommands.includes(process.argv[2] ?? '') && !(!process.argv[2] && process.stdout.isTTY)) {
1482
2129
  process.stderr.write(
1483
2130
  '\n' +
1484
2131
  '╔══════════════════════════════════════════════════════════════════╗\n' +