@cachly-dev/mcp-server 0.10.14 → 0.10.15

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 +28 -0
  6. package/LAUNCH_TEXTS.md +182 -0
  7. package/LICENSE +202 -0
  8. package/README.md +113 -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 +555 -93
  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 +29 -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 +6 -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 +599 -106
  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.15';
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,415 @@ 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 demo ──────────────────────────────────────────────────────────
1020
+ // Usage: npx @cachly-dev/mcp-server@latest demo
1021
+ // Zero-signup. Reads local git history and shows what the AI Brain would know.
1022
+ // The fastest path from "what is this?" to "I need this".
1023
+
1024
+ if (process.argv[2] === 'demo') {
1025
+ const { execSync } = await import('node:child_process');
1026
+ const { existsSync } = await import('node:fs');
1027
+ const { resolve } = await import('node:path');
1028
+ const cwd = process.cwd();
1029
+
1030
+ console.log('\n\x1b[35m🧠 cachly Brain — Live Demo\x1b[0m');
1031
+ console.log('\x1b[90mNo account needed. Reading your git history...\x1b[0m\n');
1032
+
1033
+ // Verify git repo
1034
+ if (!existsSync(resolve(cwd, '.git'))) {
1035
+ console.log('⚠️ No git repository found here.');
1036
+ console.log(' Run this command inside a project directory with git history.\n');
1037
+ console.log(' Example: cd ~/my-project && npx @cachly-dev/mcp-server@latest demo\n');
1038
+ process.exit(0);
1039
+ }
1040
+
1041
+ // Read git log
1042
+ let logOutput = '';
1043
+ try {
1044
+ logOutput = execSync(
1045
+ 'git log HEAD --pretty=format:"%H|||%s|||%ad|||%an" --date=short --no-merges -n 200',
1046
+ { cwd, encoding: 'utf-8', stdio: 'pipe' }
1047
+ );
1048
+ } catch {
1049
+ console.log('⚠️ Could not read git log. Make sure you have commits.\n');
1050
+ process.exit(0);
1051
+ }
1052
+
1053
+ const commits = logOutput.trim().split('\n').filter(Boolean).map(line => {
1054
+ const [sha, subject, date, author] = line.split('|||');
1055
+ return { sha: (sha ?? '').trim().slice(0, 8), subject: (subject ?? '').trim(), date: (date ?? '').trim(), author: (author ?? '').trim() };
1056
+ });
1057
+
1058
+ if (commits.length === 0) {
1059
+ console.log('⚠️ No commits found.\n');
1060
+ process.exit(0);
1061
+ }
1062
+
1063
+ // Classify commits (same logic as brain_from_git)
1064
+ const classify = (s: string) => {
1065
+ const t = s.toLowerCase();
1066
+ if (/\b(fix|fixed|bug|hotfix|patch|revert|resolve)\b/.test(t)) return 'fix';
1067
+ if (/\b(feat|feature|add|implement|new|introduce)\b/.test(t)) return 'feat';
1068
+ if (/\b(perf|optim|speed|cache|latency)\b/.test(t)) return 'perf';
1069
+ if (/\b(security|cve|auth|csrf|xss|inject|sanitize)\b/.test(t)) return 'security';
1070
+ if (/\b(deploy|ci|cd|docker|k8s|infra)\b/.test(t)) return 'deploy';
1071
+ if (/\b(refactor|clean|simplify|extract)\b/.test(t)) return 'refactor';
1072
+ return 'chore';
1073
+ };
1074
+
1075
+ // Count categories
1076
+ const cats = new Map<string, number>();
1077
+ const fixes: string[] = [];
1078
+ const feats: string[] = [];
1079
+ const security: string[] = [];
1080
+ const authors = new Set<string>();
1081
+
1082
+ for (const c of commits) {
1083
+ const cat = classify(c.subject);
1084
+ cats.set(cat, (cats.get(cat) ?? 0) + 1);
1085
+ if (cat === 'fix' && fixes.length < 5) fixes.push(c.subject.slice(0, 72));
1086
+ if (cat === 'feat' && feats.length < 5) feats.push(c.subject.slice(0, 72));
1087
+ if (cat === 'security' && security.length < 3) security.push(c.subject.slice(0, 72));
1088
+ if (c.author) authors.add(c.author.split(' ')[0]!);
1089
+ }
1090
+
1091
+ const totalLessons = commits.length - (cats.get('chore') ?? 0);
1092
+ const dateRange = `${commits[commits.length - 1]?.date ?? '?'} → ${commits[0]?.date ?? '?'}`;
1093
+
1094
+ // Display the demo
1095
+ process.stdout.write('\x1b[2K\r');
1096
+ console.log('┌─────────────────────────────────────────────────────────────┐');
1097
+ console.log('│ \x1b[1m🧠 Brain Preview — What your AI would know\x1b[0m │');
1098
+ console.log('├─────────────────────────────────────────────────────────────┤');
1099
+ 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 │`);
1100
+ console.log(`│ Lessons extracted: \x1b[32m${String(totalLessons).padEnd(6)}\x1b[0m Contributors: \x1b[36m${String(authors.size).padEnd(20)}\x1b[0m│`);
1101
+ console.log('├─────────────────────────────────────────────────────────────┤');
1102
+
1103
+ // Category breakdown
1104
+ const sorted = [...cats.entries()].filter(([k]) => k !== 'chore').sort((a, b) => b[1] - a[1]);
1105
+ const bar = (n: number, max: number) => '█'.repeat(Math.round((n / max) * 20)).padEnd(20);
1106
+ const maxVal = Math.max(...sorted.map(([, v]) => v), 1);
1107
+ console.log('│ \x1b[90mCategory breakdown:\x1b[0m │');
1108
+ for (const [cat, count] of sorted) {
1109
+ const emoji = { fix: '🔧', feat: '✨', perf: '⚡', security: '🔒', deploy: '🚀', refactor: '🔄' }[cat] ?? '•';
1110
+ 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 │`);
1111
+ }
1112
+
1113
+ if (security.length > 0) {
1114
+ console.log('├─────────────────────────────────────────────────────────────┤');
1115
+ console.log('│ \x1b[31m🔒 Security fixes your AI would know:\x1b[0m │');
1116
+ for (const s of security) console.log(`│ \x1b[90m• ${s.slice(0, 58).padEnd(58)}\x1b[0m │`);
1117
+ }
1118
+
1119
+ if (fixes.length > 0) {
1120
+ console.log('├─────────────────────────────────────────────────────────────┤');
1121
+ console.log('│ \x1b[33m🔧 Bug fixes your AI would remember:\x1b[0m │');
1122
+ for (const f of fixes.slice(0, 4)) console.log(`│ \x1b[90m• ${f.slice(0, 58).padEnd(58)}\x1b[0m │`);
1123
+ }
1124
+
1125
+ if (feats.length > 0) {
1126
+ console.log('├─────────────────────────────────────────────────────────────┤');
1127
+ console.log('│ \x1b[32m✨ Features & decisions it would recall:\x1b[0m │');
1128
+ for (const f of feats.slice(0, 3)) console.log(`│ \x1b[90m• ${f.slice(0, 58).padEnd(58)}\x1b[0m │`);
1129
+ }
1130
+
1131
+ console.log('├─────────────────────────────────────────────────────────────┤');
1132
+ console.log('│ \x1b[32m💡 With cachly, your AI arrives pre-briefed every session.\x1b[0m │');
1133
+ console.log('│ \x1b[32m No more re-explaining. No more repeated mistakes.\x1b[0m │');
1134
+ console.log('└─────────────────────────────────────────────────────────────┘');
1135
+ console.log('');
1136
+ console.log(' \x1b[1mMake this permanent (free, 30 seconds):\x1b[0m');
1137
+ console.log(' \x1b[32m$ npx @cachly-dev/mcp-server@latest setup\x1b[0m');
1138
+ console.log('');
1139
+ console.log(' Works with: Claude Code · Cursor · Windsurf · Copilot · Cline · Zed');
1140
+ console.log(' Free forever · GDPR · German servers · No credit card');
1141
+ console.log('');
1142
+ process.exit(0);
1143
+ }
1144
+
1145
+ // ── CLI: cachly share ─────────────────────────────────────────────────────────
1146
+ // Usage: npx @cachly-dev/mcp-server@latest share
1147
+ // Generates a shareable ASCII card + tweet text with your Brain stats.
1148
+
1149
+ if (process.argv[2] === 'share') {
1150
+ const apiKey = process.env.CACHLY_JWT ?? '';
1151
+ const instanceId = process.env.CACHLY_BRAIN_INSTANCE_ID ?? '';
1152
+
1153
+ if (!apiKey || !instanceId) {
1154
+ console.log('\n⚠️ CACHLY_JWT and CACHLY_BRAIN_INSTANCE_ID must be set.');
1155
+ console.log(' Run: npx @cachly-dev/mcp-server@latest setup (takes 30 seconds)\n');
1156
+ process.exit(1);
1157
+ }
1158
+
1159
+ process.stdout.write('\n🧠 Fetching your Brain stats...\n');
1160
+
1161
+ try {
1162
+ const statsRes = await fetch(`${API_URL}/api/v1/instances/${instanceId}/brain/stats`, {
1163
+ headers: { Authorization: `Bearer ${apiKey}` },
1164
+ signal: AbortSignal.timeout(8000),
1165
+ });
1166
+
1167
+ if (!statsRes.ok) throw new Error(`HTTP ${statsRes.status}`);
1168
+ const stats = await statsRes.json() as {
1169
+ lesson_count?: number; context_count?: number;
1170
+ quality_score?: number; total_recall_count?: number;
1171
+ };
1172
+
1173
+ const lessons = stats.lesson_count ?? 0;
1174
+ const recalls = stats.total_recall_count ?? 0;
1175
+ const score = Math.round((stats.quality_score ?? 0) * 100);
1176
+ const tokensSaved = recalls * 1200;
1177
+ const costSaved = (tokensSaved * 0.000003).toFixed(2);
1178
+
1179
+ const level = lessons === 0 ? 'Intern 🌱' :
1180
+ lessons < 10 ? 'Junior Dev 🔧' :
1181
+ lessons < 30 ? 'Mid Dev ⚡' :
1182
+ lessons < 60 ? 'Senior Dev 🧠' :
1183
+ lessons < 100 ? 'Staff Eng 🚀' : 'Principal Eng 🏆';
1184
+
1185
+ console.log('');
1186
+ console.log('┌─────────────────────────────────────────────────────────────┐');
1187
+ console.log('│ 🧠 My AI Brain · powered by \x1b[35mcachly.dev\x1b[0m │');
1188
+ console.log('├─────────────────────────────────────────────────────────────┤');
1189
+ console.log(`│ Lessons stored : \x1b[33m${String(lessons).padEnd(8)}\x1b[0m Brain level: \x1b[32m${level.padEnd(18)}\x1b[0m│`);
1190
+ console.log(`│ Total recalls : \x1b[36m${String(recalls).padEnd(8)}\x1b[0m Quality score: \x1b[32m${String(score).padEnd(3)}%\x1b[0m │`);
1191
+ 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│`);
1192
+ console.log('├─────────────────────────────────────────────────────────────┤');
1193
+ console.log('│ Works with: Claude Code · Cursor · Windsurf · Copilot │');
1194
+ console.log('│ Free · GDPR · German servers │');
1195
+ console.log('│ \x1b[35mnpx @cachly-dev/mcp-server@latest setup\x1b[0m │');
1196
+ console.log('└─────────────────────────────────────────────────────────────┘');
1197
+ console.log('');
1198
+
1199
+ // Tweet text
1200
+ 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`;
1201
+
1202
+ console.log(' \x1b[1m📋 Share on Twitter/X (copy this):\x1b[0m');
1203
+ console.log(' ─────────────────────────────────────');
1204
+ console.log(tweet.split('\n').map(l => ` ${l}`).join('\n'));
1205
+ console.log(' ─────────────────────────────────────');
1206
+ console.log('');
1207
+ console.log(' \x1b[2mPro tip: add a screenshot of your Brain panel for 3x more engagement\x1b[0m');
1208
+ console.log(' \x1b[2mAlso add a live badge to your README:\x1b[0m');
1209
+ console.log(` \x1b[90m npx @cachly-dev/mcp-server@latest badge\x1b[0m`);
1210
+ console.log('');
1211
+ } catch (e) {
1212
+ console.log(`\n❌ Could not fetch stats: ${(e as Error).message}\n`);
1213
+ process.exit(1);
1214
+ }
1215
+ process.exit(0);
1216
+ }
1217
+
1218
+ // ── CLI: cachly badge ─────────────────────────────────────────────────────────
1219
+ // Outputs the Markdown + HTML snippet for embedding a live Brain lesson-count
1220
+ // badge in any README or website. Badge SVG served by cachly API (public, no auth).
1221
+
1222
+ if (process.argv[2] === 'badge') {
1223
+ const instanceId = process.env.CACHLY_BRAIN_INSTANCE_ID ?? '';
1224
+
1225
+ if (!instanceId) {
1226
+ console.log('\n⚠️ CACHLY_BRAIN_INSTANCE_ID must be set.');
1227
+ console.log(' Run: npx @cachly-dev/mcp-server@latest setup (takes 30 seconds)\n');
1228
+ process.exit(1);
1229
+ }
1230
+
1231
+ const badgeUrl = `${API_URL}/api/v1/badge/${instanceId}`;
1232
+ const targetUrl = 'https://cachly.dev';
1233
+ const markdown = `[![cachly Brain](${badgeUrl})](${targetUrl})`;
1234
+ const htmlBadge = `<a href="${targetUrl}"><img src="${badgeUrl}" alt="cachly Brain" /></a>`;
1235
+
1236
+ console.log('');
1237
+ console.log('\x1b[35m ╔═══════════════════════════════════════════════════════╗\x1b[0m');
1238
+ console.log('\x1b[35m ║\x1b[0m \x1b[1m🧠 cachly Brain Badge\x1b[0m \x1b[35m║\x1b[0m');
1239
+ console.log('\x1b[35m ╚═══════════════════════════════════════════════════════╝\x1b[0m');
1240
+ console.log('');
1241
+ console.log(' Paste into your README.md:');
1242
+ console.log('');
1243
+ console.log(` \x1b[32m${markdown}\x1b[0m`);
1244
+ console.log('');
1245
+ console.log(' ─────────────────────────────────────────────────────');
1246
+ console.log(' Or paste into HTML:');
1247
+ console.log('');
1248
+ console.log(` \x1b[36m${htmlBadge}\x1b[0m`);
1249
+ console.log('');
1250
+ console.log(' ─────────────────────────────────────────────────────');
1251
+ console.log(' Badge URL (live, updates every hour):');
1252
+ console.log(` \x1b[90m${badgeUrl}\x1b[0m`);
1253
+ console.log('');
1254
+ console.log(' \x1b[2mThe badge shows your current lesson count — no auth required,');
1255
+ console.log(' safe to embed in public repos. Updates hourly.\x1b[0m');
1256
+ console.log('');
1257
+ process.exit(0);
1258
+ }
1259
+
1260
+ // ── CLI: no-args splash screen ────────────────────────────────────────────────
1261
+ // When run with no recognized subcommand, show a compelling pitch + help.
1262
+
1263
+ if (!process.argv[2] && process.stdout.isTTY) {
1264
+ console.log('');
1265
+ console.log('\x1b[35m ╔═══════════════════════════════════════════════════════╗\x1b[0m');
1266
+ console.log('\x1b[35m ║\x1b[0m \x1b[1m🧠 cachly — Persistent AI Memory for Developers\x1b[0m \x1b[35m║\x1b[0m');
1267
+ console.log('\x1b[35m ╚═══════════════════════════════════════════════════════╝\x1b[0m');
1268
+ console.log('');
1269
+ console.log(' Your AI forgets everything when a session ends.');
1270
+ console.log(' cachly gives it a brain that survives forever.');
1271
+ console.log('');
1272
+ console.log(' \x1b[1mCommands:\x1b[0m');
1273
+ console.log(' \x1b[32m npx @cachly-dev/mcp-server@latest demo\x1b[0m ← Start here (no account)');
1274
+ console.log(' \x1b[32m npx @cachly-dev/mcp-server@latest setup\x1b[0m ← Wire up your AI editors');
1275
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest health\x1b[0m ← Check everything works');
1276
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest digest\x1b[0m ← Weekly Brain summary');
1277
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest share\x1b[0m ← Share your Brain stats');
1278
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest badge\x1b[0m ← README badge for your Brain');
1279
+ console.log(' \x1b[36m npx @cachly-dev/mcp-server@latest invite\x1b[0m ← Invite a teammate');
1280
+ console.log('');
1281
+ console.log(' \x1b[90mWorks with: Claude Code · Cursor · Windsurf · GitHub Copilot · Cline · Zed\x1b[0m');
1282
+ console.log(' \x1b[90mFree forever · GDPR · German servers · 89 MCP tools\x1b[0m');
1283
+ console.log('');
1284
+ process.exit(0);
1285
+ }
1286
+
948
1287
  // ── CLI: cachly init ──────────────────────────────────────────────────────────
949
1288
  // Usage: npx @cachly-dev/mcp-server init --instance-id <id> --api-key <key> [--editor claude|cursor|windsurf|copilot|continue] [--project-dir /path]
950
1289
 
@@ -1018,6 +1357,158 @@ if (process.argv[2] === 'init') {
1018
1357
  process.exit(0);
1019
1358
  }
1020
1359
 
1360
+ // ── CLI: cachly health ────────────────────────────────────────────────────────
1361
+ // Usage: npx @cachly-dev/mcp-server@latest health
1362
+ // Checks: JWT valid, Brain API reachable, editor configs found, git hook present.
1363
+
1364
+ if (process.argv[2] === 'health') {
1365
+ const { existsSync } = await import('node:fs');
1366
+ const { readFile } = await import('node:fs/promises');
1367
+ const { resolve, join: pJoin } = await import('node:path');
1368
+
1369
+ const cwd = process.cwd();
1370
+ let passed = 0;
1371
+ let failed = 0;
1372
+
1373
+ const ok = (msg: string) => { console.log(` ✅ ${msg}`); passed++; };
1374
+ const warn = (msg: string) => { console.log(` ⚠️ ${msg}`); };
1375
+ const fail = (msg: string) => { console.log(` ❌ ${msg}`); failed++; };
1376
+
1377
+ console.log('\n🧠 cachly health check\n');
1378
+
1379
+ // ── 1. JWT token ────────────────────────────────────────────────────────────
1380
+ console.log('🔑 Auth token');
1381
+ const jwt = process.env.CACHLY_JWT ?? '';
1382
+ if (!jwt) {
1383
+ fail('CACHLY_JWT not set — run: npx @cachly-dev/mcp-server@latest setup');
1384
+ } else {
1385
+ try {
1386
+ const parts = jwt.split('.');
1387
+ if (parts.length !== 3) throw new Error('not a JWT');
1388
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf-8')) as {
1389
+ sub?: string; exp?: number;
1390
+ };
1391
+ const expMs = payload.exp ? payload.exp * 1000 : null;
1392
+ const minsLeft = expMs ? Math.floor((expMs - Date.now()) / 60_000) : null;
1393
+ if (expMs && expMs < Date.now()) {
1394
+ fail(`JWT expired ${Math.abs(minsLeft!)} minute(s) ago — get a new one: https://cachly.dev/setup-ai`);
1395
+ } else if (minsLeft !== null && minsLeft < 30) {
1396
+ warn(`JWT expires in ${minsLeft} minute(s) — refresh soon at https://cachly.dev/setup-ai`);
1397
+ } else {
1398
+ ok(`JWT valid${minsLeft !== null ? ` (expires in ${Math.floor(minsLeft / 60)}h ${minsLeft % 60}m)` : ''}`);
1399
+ }
1400
+ } catch {
1401
+ fail('CACHLY_JWT format invalid (expected JWT with 3 parts)');
1402
+ }
1403
+ }
1404
+
1405
+ // ── 2. Brain API reachability ───────────────────────────────────────────────
1406
+ console.log('\n🌐 Brain API');
1407
+ const apiUrl = process.env.CACHLY_API_URL ?? 'https://api.cachly.dev';
1408
+ try {
1409
+ const res = await fetch(`${apiUrl}/health`, { signal: AbortSignal.timeout(5000) });
1410
+ if (res.ok) {
1411
+ const body = await res.json() as { status?: string };
1412
+ ok(`${apiUrl} reachable (status: ${body.status ?? 'ok'})`);
1413
+ } else if (res.status === 401 || res.status === 403) {
1414
+ ok(`${apiUrl} reachable (auth required — expected)`);
1415
+ } else {
1416
+ fail(`${apiUrl}/health returned HTTP ${res.status}`);
1417
+ }
1418
+ } catch (e) {
1419
+ fail(`${apiUrl} unreachable — ${(e as Error).message}`);
1420
+ }
1421
+
1422
+ // ── 3. Brain instance ───────────────────────────────────────────────────────
1423
+ console.log('\n🧠 Brain instance');
1424
+ const instanceId = process.env.CACHLY_BRAIN_INSTANCE_ID ?? '';
1425
+ if (!instanceId) {
1426
+ warn('CACHLY_BRAIN_INSTANCE_ID not set — will auto-resolve on first tool call');
1427
+ } else if (jwt) {
1428
+ try {
1429
+ const instRes = await fetch(`${apiUrl}/api/v1/instances/${instanceId}`, {
1430
+ headers: { Authorization: `Bearer ${jwt}`, Accept: 'application/json' },
1431
+ signal: AbortSignal.timeout(5000),
1432
+ });
1433
+ if (instRes.ok) {
1434
+ const inst = await instRes.json() as { name?: string; status?: string };
1435
+ if (inst.status === 'running') {
1436
+ ok(`Instance "${inst.name}" (${instanceId.slice(0, 8)}…) is running`);
1437
+ } else {
1438
+ warn(`Instance "${inst.name}" status: ${inst.status}`);
1439
+ }
1440
+ } else {
1441
+ fail(`Instance ${instanceId.slice(0, 8)}… not found (HTTP ${instRes.status})`);
1442
+ }
1443
+ } catch (e) {
1444
+ fail(`Could not check instance — ${(e as Error).message}`);
1445
+ }
1446
+ }
1447
+
1448
+ // ── 4. Editor configs ───────────────────────────────────────────────────────
1449
+ console.log('\n🛠 Editor configs (project dir)');
1450
+ const editorConfigs: Array<{ editor: string; path: string }> = [
1451
+ { editor: 'Claude Code', path: '.mcp.json' },
1452
+ { editor: 'Cursor', path: '.cursor/mcp.json' },
1453
+ { editor: 'Windsurf', path: '.windsurf/mcp.json' },
1454
+ { editor: 'Copilot / Cline', path: '.vscode/mcp.json' },
1455
+ { editor: 'Zed', path: '.zed/settings.json' },
1456
+ { editor: 'Continue.dev', path: '.continue/config.json' },
1457
+ ];
1458
+ let configsFound = 0;
1459
+ for (const { editor, path } of editorConfigs) {
1460
+ const fullPath = resolve(cwd, path);
1461
+ if (existsSync(fullPath)) {
1462
+ try {
1463
+ const content = await readFile(fullPath, 'utf-8');
1464
+ const hasCachly = content.includes('@cachly-dev/mcp-server') || content.includes('cachly');
1465
+ if (hasCachly) {
1466
+ ok(`${editor}: ${path}`);
1467
+ configsFound++;
1468
+ } else {
1469
+ warn(`${editor}: ${path} exists but cachly not found inside`);
1470
+ }
1471
+ } catch {
1472
+ warn(`${editor}: ${path} exists but could not read`);
1473
+ }
1474
+ }
1475
+ }
1476
+ if (configsFound === 0) {
1477
+ fail('No editor MCP configs found — run: npx @cachly-dev/mcp-server@latest setup');
1478
+ }
1479
+
1480
+ // ── 5. Git hook ─────────────────────────────────────────────────────────────
1481
+ console.log('\n🪝 Git hook (ambient learning)');
1482
+ const hookPath = resolve(cwd, '.git', 'hooks', 'post-commit');
1483
+ if (!existsSync(resolve(cwd, '.git'))) {
1484
+ warn('Not in a git repository — skip');
1485
+ } else if (existsSync(hookPath)) {
1486
+ try {
1487
+ const hook = await readFile(hookPath, 'utf-8');
1488
+ if (hook.includes('cachly')) {
1489
+ ok('.git/hooks/post-commit (cachly CLS hook present)');
1490
+ } else {
1491
+ warn('.git/hooks/post-commit exists but cachly hook not found — run setup to add it');
1492
+ }
1493
+ } catch {
1494
+ warn('.git/hooks/post-commit exists but could not read');
1495
+ }
1496
+ } else {
1497
+ warn('.git/hooks/post-commit not found — run: npx @cachly-dev/mcp-server@latest setup');
1498
+ }
1499
+
1500
+ // ── Summary ─────────────────────────────────────────────────────────────────
1501
+ console.log(`\n${'─'.repeat(40)}`);
1502
+ if (failed === 0) {
1503
+ console.log(`✅ All checks passed (${passed} ok)\n`);
1504
+ } else {
1505
+ console.log(`❌ ${failed} check(s) failed, ${passed} passed\n`);
1506
+ console.log(`💡 Fix issues with: npx @cachly-dev/mcp-server@latest setup\n`);
1507
+ process.exit(1);
1508
+ }
1509
+ process.exit(0);
1510
+ }
1511
+
1021
1512
  // ── CLI: cachly setup (interactive — no flags required) ───────────────────────
1022
1513
  // Usage: npx @cachly-dev/mcp-server setup
1023
1514
 
@@ -1478,7 +1969,9 @@ if (process.argv[2] === 'index') {
1478
1969
 
1479
1970
  // Warn on stderr when credentials are missing so the user sees a clear
1480
1971
  // actionable message in their editor's MCP log instead of silent failures.
1481
- if (!JWT) {
1972
+ // Skip for CLI commands that intentionally run without credentials.
1973
+ const _cliNoAuthCommands = ['demo', 'share', 'health', 'setup', 'init', 'digest', 'invite', 'badge'];
1974
+ if (!JWT && !_cliNoAuthCommands.includes(process.argv[2] ?? '') && !(!process.argv[2] && process.stdout.isTTY)) {
1482
1975
  process.stderr.write(
1483
1976
  '\n' +
1484
1977
  '╔══════════════════════════════════════════════════════════════════╗\n' +