cortex-mcp 2.5.0 → 2.6.0

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 (42) hide show
  1. package/dist/memory/access-pattern-tracker.d.ts +51 -0
  2. package/dist/memory/access-pattern-tracker.d.ts.map +1 -0
  3. package/dist/memory/access-pattern-tracker.js +92 -0
  4. package/dist/memory/access-pattern-tracker.js.map +1 -0
  5. package/dist/memory/cross-memory-linker.d.ts +18 -0
  6. package/dist/memory/cross-memory-linker.d.ts.map +1 -0
  7. package/dist/memory/cross-memory-linker.js +115 -0
  8. package/dist/memory/cross-memory-linker.js.map +1 -0
  9. package/dist/memory/daily-diary.d.ts +30 -0
  10. package/dist/memory/daily-diary.d.ts.map +1 -0
  11. package/dist/memory/daily-diary.js +159 -0
  12. package/dist/memory/daily-diary.js.map +1 -0
  13. package/dist/memory/embedding-cache.d.ts +32 -0
  14. package/dist/memory/embedding-cache.d.ts.map +1 -0
  15. package/dist/memory/embedding-cache.js +76 -0
  16. package/dist/memory/embedding-cache.js.map +1 -0
  17. package/dist/memory/memory-decay.d.ts.map +1 -1
  18. package/dist/memory/memory-decay.js +10 -6
  19. package/dist/memory/memory-decay.js.map +1 -1
  20. package/dist/memory/memory-export-md.d.ts +12 -0
  21. package/dist/memory/memory-export-md.d.ts.map +1 -0
  22. package/dist/memory/memory-export-md.js +188 -0
  23. package/dist/memory/memory-export-md.js.map +1 -0
  24. package/dist/memory/memory-ranker.d.ts.map +1 -1
  25. package/dist/memory/memory-ranker.js +7 -2
  26. package/dist/memory/memory-ranker.js.map +1 -1
  27. package/dist/memory/mmr-reranker.d.ts +39 -0
  28. package/dist/memory/mmr-reranker.d.ts.map +1 -0
  29. package/dist/memory/mmr-reranker.js +115 -0
  30. package/dist/memory/mmr-reranker.js.map +1 -0
  31. package/dist/memory/query-expansion.d.ts +28 -0
  32. package/dist/memory/query-expansion.d.ts.map +1 -0
  33. package/dist/memory/query-expansion.js +140 -0
  34. package/dist/memory/query-expansion.js.map +1 -0
  35. package/dist/memory/soul-manager.d.ts +30 -0
  36. package/dist/memory/soul-manager.d.ts.map +1 -0
  37. package/dist/memory/soul-manager.js +171 -0
  38. package/dist/memory/soul-manager.js.map +1 -0
  39. package/dist/server/mcp-handler.d.ts.map +1 -1
  40. package/dist/server/mcp-handler.js +103 -48
  41. package/dist/server/mcp-handler.js.map +1 -1
  42. package/package.json +1 -1
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ /**
3
+ * Query Expansion — Smarter search like OpenClaw's query-expansion.ts.
4
+ *
5
+ * Problem: User searches for "authentication bug" but the memory
6
+ * says "login issue with JWT tokens." Raw search misses it.
7
+ *
8
+ * Solution: Expand the query with synonyms and related terms:
9
+ * "authentication bug" → "authentication auth login bug error issue fix"
10
+ *
11
+ * This is OpenClaw's approach — extract keywords and add related terms
12
+ * so both FTS and vector search find more relevant results.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.expandQuery = expandQuery;
16
+ exports.extractKeyTerms = extractKeyTerms;
17
+ exports.generateAlternativeQueries = generateAlternativeQueries;
18
+ /**
19
+ * Expand a query with synonyms and related programming terms.
20
+ * Returns the original query plus expanded terms.
21
+ */
22
+ function expandQuery(query) {
23
+ const words = query.toLowerCase().split(/\s+/).filter(w => w.length > 1);
24
+ const expanded = new Set(words);
25
+ for (const word of words) {
26
+ const synonyms = SYNONYM_MAP[word];
27
+ if (synonyms) {
28
+ for (const syn of synonyms) {
29
+ expanded.add(syn);
30
+ }
31
+ }
32
+ }
33
+ return Array.from(expanded).join(' ');
34
+ }
35
+ /**
36
+ * Extract key technical terms from a query for targeted search.
37
+ * Filters out stop words and generic terms, keeping only meaningful tokens.
38
+ */
39
+ function extractKeyTerms(query) {
40
+ return query.toLowerCase()
41
+ .replace(/[^a-z0-9\s_-]/g, ' ')
42
+ .split(/\s+/)
43
+ .filter(w => w.length > 2 && !STOP_WORDS.has(w));
44
+ }
45
+ /**
46
+ * Generate alternative search queries for better recall.
47
+ * Returns the original plus 1-2 reformulated queries.
48
+ */
49
+ function generateAlternativeQueries(query) {
50
+ const queries = [query];
51
+ const lower = query.toLowerCase();
52
+ // If asking "how to X" → also search for "X implementation"
53
+ const howToMatch = lower.match(/how\s+to\s+(.+)/);
54
+ if (howToMatch) {
55
+ queries.push(`${howToMatch[1]} implementation`);
56
+ queries.push(`${howToMatch[1]} pattern`);
57
+ }
58
+ // If asking about "error" → also search for "bug fix"
59
+ if (lower.includes('error') || lower.includes('bug')) {
60
+ queries.push(lower.replace(/error|bug/g, 'fix correction'));
61
+ }
62
+ // If asking about "why" → search for decisions
63
+ if (lower.startsWith('why')) {
64
+ queries.push(lower.replace('why', 'decision reason'));
65
+ }
66
+ return queries.slice(0, 3); // Max 3 alternatives
67
+ }
68
+ // ─── Synonym Map for Programming Terms ──────────────────────────────────────
69
+ const SYNONYM_MAP = {
70
+ // Authentication
71
+ 'auth': ['authentication', 'login', 'signin', 'jwt', 'token', 'session'],
72
+ 'authentication': ['auth', 'login', 'signin', 'jwt'],
73
+ 'login': ['auth', 'authentication', 'signin'],
74
+ 'logout': ['signout', 'session'],
75
+ // Database
76
+ 'database': ['db', 'sql', 'query', 'schema', 'migration'],
77
+ 'db': ['database', 'sql', 'query'],
78
+ 'sql': ['database', 'query', 'schema'],
79
+ 'migration': ['database', 'schema', 'alter'],
80
+ 'schema': ['database', 'model', 'table'],
81
+ // API
82
+ 'api': ['endpoint', 'route', 'rest', 'request', 'response'],
83
+ 'endpoint': ['api', 'route', 'handler'],
84
+ 'route': ['api', 'endpoint', 'path', 'handler'],
85
+ 'request': ['req', 'http', 'fetch'],
86
+ 'response': ['res', 'http', 'reply'],
87
+ // Errors & Debugging
88
+ 'error': ['bug', 'issue', 'exception', 'crash', 'failure', 'fix'],
89
+ 'bug': ['error', 'issue', 'defect', 'fix', 'correction'],
90
+ 'fix': ['repair', 'correction', 'patch', 'resolve'],
91
+ 'crash': ['error', 'exception', 'failure', 'abort'],
92
+ 'debug': ['troubleshoot', 'diagnose', 'inspect', 'trace'],
93
+ // Testing
94
+ 'test': ['testing', 'spec', 'unit', 'jest', 'mocha', 'vitest'],
95
+ 'testing': ['test', 'spec', 'assertion', 'mock'],
96
+ 'mock': ['stub', 'fake', 'spy', 'test'],
97
+ // Architecture
98
+ 'component': ['module', 'widget', 'element'],
99
+ 'module': ['component', 'package', 'library'],
100
+ 'pattern': ['architecture', 'design', 'structure'],
101
+ 'refactor': ['restructure', 'cleanup', 'reorganize'],
102
+ // Frontend
103
+ 'style': ['css', 'styling', 'theme', 'design'],
104
+ 'css': ['style', 'stylesheet', 'tailwind'],
105
+ 'ui': ['interface', 'frontend', 'view', 'component'],
106
+ 'layout': ['grid', 'flex', 'responsive', 'design'],
107
+ // State
108
+ 'state': ['store', 'context', 'redux', 'zustand'],
109
+ 'cache': ['memo', 'memoize', 'store', 'buffer'],
110
+ // Config
111
+ 'config': ['configuration', 'settings', 'options', 'env'],
112
+ 'env': ['environment', 'config', 'dotenv', 'variable'],
113
+ // Performance
114
+ 'performance': ['speed', 'optimize', 'fast', 'slow', 'latency'],
115
+ 'optimize': ['performance', 'improve', 'speed', 'efficient'],
116
+ 'slow': ['performance', 'latency', 'bottleneck', 'optimize'],
117
+ // Security
118
+ 'security': ['auth', 'encryption', 'vulnerability', 'xss', 'csrf'],
119
+ 'encrypt': ['hash', 'security', 'cipher', 'bcrypt'],
120
+ // TypeScript
121
+ 'type': ['interface', 'typescript', 'generic', 'typing'],
122
+ 'interface': ['type', 'contract', 'shape', 'typescript'],
123
+ 'generic': ['type', 'template', 'parameterized'],
124
+ // Deployment
125
+ 'deploy': ['deployment', 'release', 'publish', 'ship'],
126
+ 'ci': ['pipeline', 'github-actions', 'workflow', 'build'],
127
+ };
128
+ const STOP_WORDS = new Set([
129
+ 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being',
130
+ 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',
131
+ 'should', 'may', 'might', 'can', 'shall', 'to', 'of', 'in', 'for',
132
+ 'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',
133
+ 'this', 'that', 'these', 'those', 'it', 'its', 'not', 'no', 'but',
134
+ 'or', 'and', 'if', 'then', 'else', 'when', 'up', 'out', 'about',
135
+ 'so', 'all', 'each', 'every', 'both', 'few', 'more', 'most', 'other',
136
+ 'some', 'such', 'only', 'own', 'same', 'than', 'too', 'very',
137
+ 'just', 'because', 'before', 'after', 'above', 'below', 'between',
138
+ 'what', 'which', 'who', 'whom', 'how', 'where', 'there', 'here',
139
+ ]);
140
+ //# sourceMappingURL=query-expansion.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-expansion.js","sourceRoot":"","sources":["../../src/memory/query-expansion.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;AAMH,kCAcC;AAMD,0CAKC;AAMD,gEAsBC;AAzDD;;;GAGG;AACH,SAAgB,WAAW,CAAC,KAAa;IACrC,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACzE,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAEhC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,MAAM,QAAQ,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,QAAQ,EAAE,CAAC;YACX,KAAK,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;gBACzB,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACtB,CAAC;QACL,CAAC;IACL,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC1C,CAAC;AAED;;;GAGG;AACH,SAAgB,eAAe,CAAC,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AAI,EAAE,IAAI,EAAE,KAAK;IACjE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ;IACnE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK;IACjE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO;IAC/D,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IACpE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;IAC5D,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS;IACjE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM;CAClE,CAAC,CAAC"}
@@ -0,0 +1,30 @@
1
+ export interface SoulEntry {
2
+ category: string;
3
+ content: string;
4
+ }
5
+ /**
6
+ * Load SOUL.md from workspace. Returns content or null.
7
+ */
8
+ export declare function loadSoul(workspaceRoot: string): string | null;
9
+ /**
10
+ * Initialize SOUL.md with default template if it doesn't exist.
11
+ */
12
+ export declare function initSoul(workspaceRoot: string): string;
13
+ /**
14
+ * Update soul by appending a new entry under the right category.
15
+ */
16
+ export declare function updateSoul(workspaceRoot: string, entry: SoulEntry): void;
17
+ /**
18
+ * Format soul content for injection into force_recall (Layer 0).
19
+ */
20
+ export declare function formatSoul(workspaceRoot: string): string;
21
+ /**
22
+ * Auto-learn from memories to build soul entries.
23
+ * Called periodically — extracts strong conventions and rules.
24
+ */
25
+ export declare function autoLearnSoul(workspaceRoot: string, memories: Array<{
26
+ type: string;
27
+ intent: string;
28
+ accessCount?: number;
29
+ }>): void;
30
+ //# sourceMappingURL=soul-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"soul-manager.d.ts","sourceRoot":"","sources":["../../src/memory/soul-manager.ts"],"names":[],"mappings":"AAgBA,MAAM,WAAW,SAAS;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACnB;AAuBD;;GAEG;AACH,wBAAgB,QAAQ,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAQ7D;AAED;;GAEG;AACH,wBAAgB,QAAQ,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAWtD;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,aAAa,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CAoBxE;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CASxD;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,IAAI,CAelI"}
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.loadSoul = loadSoul;
37
+ exports.initSoul = initSoul;
38
+ exports.updateSoul = updateSoul;
39
+ exports.formatSoul = formatSoul;
40
+ exports.autoLearnSoul = autoLearnSoul;
41
+ /**
42
+ * Soul Manager — OpenClaw-style persistent identity layer.
43
+ *
44
+ * Creates and maintains a SOUL.md file in the workspace that stores:
45
+ * - User's coding preferences ("always use TypeScript strict mode")
46
+ * - Project conventions ("we use PostgreSQL, never MongoDB")
47
+ * - Identity ("Senior Backend Engineer working on e-commerce platform")
48
+ *
49
+ * This is injected as Layer 0 in force_recall — the very first thing the AI sees.
50
+ * Unlike transient memories, the Soul NEVER decays.
51
+ *
52
+ * Inspired by OpenClaw's SOUL.md / IDENTITY.md architecture.
53
+ */
54
+ const fs = __importStar(require("fs"));
55
+ const path = __importStar(require("path"));
56
+ const DEFAULT_SOUL = `# 🧠 Cortex Soul — Who I Am
57
+
58
+ > This file is your AI's persistent identity. Edit it freely.
59
+ > Cortex reads this at the start of every session.
60
+
61
+ ## Identity
62
+ - (Add your role: e.g., "Senior TypeScript developer")
63
+ - (Add your project: e.g., "Building an e-commerce platform")
64
+
65
+ ## Conventions
66
+ - (Add team rules: e.g., "Always use strict TypeScript, never \`any\`")
67
+ - (Add stack: e.g., "PostgreSQL, Redis, Next.js 14")
68
+
69
+ ## Preferences
70
+ - (Add style: e.g., "Prefer functional over OOP")
71
+ - (Add tools: e.g., "Use pnpm, not npm")
72
+
73
+ ## Rules (Never Break)
74
+ - (Add hard rules: e.g., "Never delete user data without confirmation")
75
+ `;
76
+ /**
77
+ * Load SOUL.md from workspace. Returns content or null.
78
+ */
79
+ function loadSoul(workspaceRoot) {
80
+ const soulPath = getSoulPath(workspaceRoot);
81
+ try {
82
+ if (fs.existsSync(soulPath)) {
83
+ return fs.readFileSync(soulPath, 'utf-8').trim();
84
+ }
85
+ }
86
+ catch { /* file not readable */ }
87
+ return null;
88
+ }
89
+ /**
90
+ * Initialize SOUL.md with default template if it doesn't exist.
91
+ */
92
+ function initSoul(workspaceRoot) {
93
+ const soulPath = getSoulPath(workspaceRoot);
94
+ try {
95
+ const dir = path.dirname(soulPath);
96
+ if (!fs.existsSync(dir))
97
+ fs.mkdirSync(dir, { recursive: true });
98
+ if (!fs.existsSync(soulPath)) {
99
+ fs.writeFileSync(soulPath, DEFAULT_SOUL, 'utf-8');
100
+ return DEFAULT_SOUL;
101
+ }
102
+ return fs.readFileSync(soulPath, 'utf-8').trim();
103
+ }
104
+ catch {
105
+ return '';
106
+ }
107
+ }
108
+ /**
109
+ * Update soul by appending a new entry under the right category.
110
+ */
111
+ function updateSoul(workspaceRoot, entry) {
112
+ const soulPath = getSoulPath(workspaceRoot);
113
+ try {
114
+ let content = loadSoul(workspaceRoot) || DEFAULT_SOUL;
115
+ const sectionMap = {
116
+ 'identity': '## Identity',
117
+ 'convention': '## Conventions',
118
+ 'preference': '## Preferences',
119
+ 'rule': '## Rules (Never Break)',
120
+ };
121
+ const header = sectionMap[entry.category] || '## Preferences';
122
+ const idx = content.indexOf(header);
123
+ if (idx >= 0) {
124
+ const insertAt = content.indexOf('\n', idx) + 1;
125
+ content = content.slice(0, insertAt) + `- ${entry.content}\n` + content.slice(insertAt);
126
+ }
127
+ else {
128
+ content += `\n${header}\n- ${entry.content}\n`;
129
+ }
130
+ fs.writeFileSync(soulPath, content, 'utf-8');
131
+ }
132
+ catch { /* non-fatal */ }
133
+ }
134
+ /**
135
+ * Format soul content for injection into force_recall (Layer 0).
136
+ */
137
+ function formatSoul(workspaceRoot) {
138
+ const soul = loadSoul(workspaceRoot);
139
+ if (!soul || soul.includes('(Add your role'))
140
+ return ''; // Still default template
141
+ // Strip the header explanation, keep only the actual content
142
+ const lines = soul.split('\n').filter(l => l.trim() && !l.startsWith('>') && !l.includes('(Add your'));
143
+ if (lines.length <= 1)
144
+ return '';
145
+ return `\n## 🧬 Soul (Persistent Identity)\n${lines.join('\n')}`;
146
+ }
147
+ /**
148
+ * Auto-learn from memories to build soul entries.
149
+ * Called periodically — extracts strong conventions and rules.
150
+ */
151
+ function autoLearnSoul(workspaceRoot, memories) {
152
+ try {
153
+ const soul = loadSoul(workspaceRoot) || '';
154
+ const strongConventions = memories.filter(m => (m.type === 'CONVENTION' || m.type === 'DECISION') &&
155
+ (m.accessCount || 0) >= 3 && // Accessed multiple times = important
156
+ !soul.includes(m.intent.slice(0, 40)) // Not already in soul
157
+ );
158
+ for (const m of strongConventions.slice(0, 3)) {
159
+ updateSoul(workspaceRoot, {
160
+ category: m.type === 'CONVENTION' ? 'convention' : 'preference',
161
+ content: m.intent.slice(0, 150),
162
+ });
163
+ }
164
+ }
165
+ catch { /* non-fatal */ }
166
+ }
167
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
168
+ function getSoulPath(workspaceRoot) {
169
+ return path.join(workspaceRoot, '.cortex', 'SOUL.md');
170
+ }
171
+ //# sourceMappingURL=soul-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"soul-manager.js","sourceRoot":"","sources":["../../src/memory/soul-manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,4BAQC;AAKD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AAe,CAAC,CAAC;AAC/B,CAAC;AAED,iFAAiF;AAEjF,SAAS,WAAW,CAAC,aAAqB;IACtC,OAAO,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;AAC1D,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-handler.d.ts","sourceRoot":"","sources":["../../src/server/mcp-handler.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAyT3C,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE,aAAa,CAAC,EAAE,MAAM;4BAC5D,GAAG,KAAG,OAAO,CAAC,GAAG,CAAC;EAk5D1D"}
1
+ {"version":3,"file":"mcp-handler.d.ts","sourceRoot":"","sources":["../../src/server/mcp-handler.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAsS3C,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE,aAAa,CAAC,EAAE,MAAM;4BAC5D,GAAG,KAAG,OAAO,CAAC,GAAG,CAAC;EA88D1D"}
@@ -33,6 +33,14 @@ const error_learner_1 = require("../memory/error-learner");
33
33
  const completion_resolver_1 = require("../memory/completion-resolver");
34
34
  const pre_flight_1 = require("../memory/pre-flight");
35
35
  const impact_analyzer_1 = require("../memory/impact-analyzer");
36
+ const cross_memory_linker_1 = require("../memory/cross-memory-linker");
37
+ const access_pattern_tracker_1 = require("../memory/access-pattern-tracker");
38
+ const soul_manager_1 = require("../memory/soul-manager");
39
+ const daily_diary_1 = require("../memory/daily-diary");
40
+ const memory_export_md_1 = require("../memory/memory-export-md");
41
+ const mmr_reranker_1 = require("../memory/mmr-reranker");
42
+ const embedding_cache_1 = require("../memory/embedding-cache");
43
+ const query_expansion_1 = require("../memory/query-expansion");
36
44
  const resume_work_1 = require("../memory/resume-work");
37
45
  const preference_learner_1 = require("../memory/preference-learner");
38
46
  const convention_detector_1 = require("../memory/convention-detector");
@@ -41,35 +49,9 @@ const file_relationships_1 = require("../memory/file-relationships");
41
49
  const instructions_generator_1 = require("../memory/instructions-generator");
42
50
  const tool_recommender_1 = require("../memory/tool-recommender");
43
51
  const regression_guard_1 = require("../memory/regression-guard");
44
- // --- Query Expansion (Synonym Map) ---
45
- const SYNONYMS = {
46
- auth: ['authentication', 'login', 'signin', 'sign-in', 'credentials'],
47
- login: ['auth', 'authentication', 'signin', 'sign-in'],
48
- db: ['database', 'sql', 'postgresql', 'postgres', 'mongodb', 'sqlite'],
49
- database: ['db', 'sql', 'postgresql', 'postgres', 'mongodb', 'sqlite'],
50
- api: ['endpoint', 'route', 'rest', 'graphql', 'http'],
51
- error: ['bug', 'fix', 'issue', 'problem', 'crash', 'fail'],
52
- bug: ['error', 'fix', 'issue', 'problem', 'crash'],
53
- style: ['css', 'design', 'theme', 'color', 'font', 'layout'],
54
- test: ['testing', 'jest', 'vitest', 'spec', 'unittest'],
55
- deploy: ['deployment', 'ci', 'cd', 'pipeline', 'docker', 'build'],
56
- };
52
+ // --- OpenClaw-style Query Expansion (replaced basic synonym map) ---
57
53
  function expandQuery(query) {
58
- const words = query.toLowerCase().split(/\s+/).filter(w => w.length > 2);
59
- const expanded = new Set(words);
60
- for (const word of words) {
61
- if (expanded.size >= 8)
62
- break; // Cap expansion to prevent FTS hang
63
- const syns = SYNONYMS[word];
64
- if (syns) {
65
- for (const s of syns.slice(0, 2)) {
66
- if (expanded.size >= 8)
67
- break;
68
- expanded.add(s);
69
- }
70
- }
71
- }
72
- return Array.from(expanded).join(' OR ');
54
+ return (0, query_expansion_1.expandQuery)(query);
73
55
  }
74
56
  // --- MCP Tool Definitions ---
75
57
  const MCP_TOOLS = [
@@ -580,23 +562,39 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
580
562
  if (ftsResults.length === 0) {
581
563
  ftsResults = memoryStore.searchFTS(queryText, maxResults * 2);
582
564
  }
565
+ // OpenClaw: Try alternative queries if still 0 results
566
+ if (ftsResults.length === 0) {
567
+ const altQueries = (0, query_expansion_1.generateAlternativeQueries)(queryText);
568
+ for (const alt of altQueries.slice(1)) { // skip first (original)
569
+ ftsResults = memoryStore.searchFTS(alt, maxResults * 2);
570
+ if (ftsResults.length > 0)
571
+ break;
572
+ }
573
+ }
583
574
  console.log(` [FTS] ${ftsResults.length} results`);
584
- // 2. Vector Search (if worker ready)
575
+ // 2. Vector Search (if worker ready) — with OpenClaw-style embedding cache
585
576
  let vectorResults = [];
586
577
  if ((0, embedding_manager_1.isWorkerReady)()) {
587
- const embedding = await (0, embedding_manager_1.embedText)(queryText);
588
- vectorResults = memoryStore.searchVector(new Float32Array(embedding), maxResults * 2);
578
+ // Check cache first (OpenClaw pattern)
579
+ let embeddingArr = (0, embedding_cache_1.getCachedEmbedding)(queryText);
580
+ if (!embeddingArr) {
581
+ embeddingArr = await (0, embedding_manager_1.embedText)(queryText);
582
+ (0, embedding_cache_1.cacheEmbedding)(queryText, embeddingArr);
583
+ }
584
+ vectorResults = memoryStore.searchVector(new Float32Array(embeddingArr), maxResults * 2);
589
585
  if (vectorResults.length > 0) {
590
586
  console.log(` [VECTOR] ${vectorResults.length} results`);
591
587
  }
592
588
  }
593
589
  // 3. Hybrid Ranking
594
590
  const rawRanked = (0, memory_ranker_1.rankResults)(ftsResults, vectorResults, maxResults * 2, currentFile);
595
- // Map RankedResult to ScoredMemory
596
- ranked = rawRanked.map(r => ({
591
+ // 3a. Apply MMR re-ranking (OpenClaw-style diversity)
592
+ const mmrRanked = (0, mmr_reranker_1.applyMMR)(rawRanked.map(r => ({
597
593
  ...r,
598
594
  matchMethod: 'hybrid'
599
- }));
595
+ })));
596
+ // Map to ScoredMemory
597
+ ranked = mmrRanked;
600
598
  // 3b. Project-aware boost (memories from current project rank higher)
601
599
  if (workspaceRoot) {
602
600
  try {
@@ -663,6 +661,8 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
663
661
  catch { /* non-fatal */ }
664
662
  }
665
663
  });
664
+ // NEW: Record access patterns for personalized boosting
665
+ (0, access_pattern_tracker_1.recordBatchAccess)(ranked.map(r => ({ type: r.memory.type })));
666
666
  (0, confidence_decay_1.runDecayMaintenance)(memoryStore); // Opportunistic decay
667
667
  }
668
668
  (0, memory_cache_1.setCache)(cacheKey, ranked);
@@ -772,25 +772,24 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
772
772
  }
773
773
  }
774
774
  catch { /* non-fatal */ }
775
- // Auto-edge creationlink to recent memories of same type/files
775
+ // Smart cross-memory linkingconnects by files, tags, AND word overlap
776
776
  try {
777
- const recent = memoryStore.getByType(memType, 5);
778
- for (const r of recent) {
779
- if (r.id !== memory.id) {
780
- memoryStore.addEdge({
781
- sourceId: memory.id,
782
- targetId: r.id,
783
- relation: 'related_to',
784
- weight: 0.5,
785
- timestamp: Date.now(),
786
- });
787
- break; // Link to most recent only
788
- }
789
- }
777
+ const linksCreated = (0, cross_memory_linker_1.autoLinkMemory)(memoryStore, memory);
778
+ if (linksCreated > 0)
779
+ console.log(` [LINK] Auto-linked ${linksCreated} related memories`);
790
780
  }
791
781
  catch { /* non-fatal */ }
792
782
  // Feed session tracker
793
783
  (0, session_tracker_1.feedSession)({ decision: `[${type}] ${sanitized.slice(0, 60)}` });
784
+ // OpenClaw: Log to daily diary (store_memory path)
785
+ try {
786
+ (0, daily_diary_1.appendDiaryEntry)({
787
+ type: type.toLowerCase().replace('_', '_'),
788
+ content: sanitized.slice(0, 100),
789
+ file: files?.[0],
790
+ });
791
+ }
792
+ catch { /* diary is non-critical */ }
794
793
  // Queue background embedding
795
794
  if ((0, embedding_manager_1.isWorkerReady)()) {
796
795
  const embedText_ = [sanitized, reason || ''].join(' ').trim();
@@ -1152,6 +1151,16 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
1152
1151
  (0, usage_stats_1.resetSessionStats)();
1153
1152
  if (args.topic)
1154
1153
  (0, session_tracker_1.feedSession)({ topic: args.topic });
1154
+ // ─── SOUL LAYER (OpenClaw-style identity) ────────────────────────
1155
+ if (workspaceRoot) {
1156
+ try {
1157
+ (0, soul_manager_1.initSoul)(workspaceRoot);
1158
+ const soulContext = (0, soul_manager_1.formatSoul)(workspaceRoot);
1159
+ if (soulContext)
1160
+ parts.push(soulContext);
1161
+ }
1162
+ catch { /* soul is non-critical */ }
1163
+ }
1155
1164
  // ─── Project Detection (for project isolation) ───────────────────
1156
1165
  let projectName = '';
1157
1166
  if (workspaceRoot) {
@@ -1208,6 +1217,24 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
1208
1217
  if ((0, memory_consolidator_1.shouldConsolidate)(memoryStore)) {
1209
1218
  (0, memory_consolidator_1.consolidateMemories)(memoryStore);
1210
1219
  }
1220
+ // OpenClaw: Auto-learn soul from high-access memories
1221
+ if (workspaceRoot) {
1222
+ const topMemories = memoryStore.getActive(50).map(m => ({
1223
+ type: m.type, intent: m.intent, accessCount: m.accessCount
1224
+ }));
1225
+ (0, soul_manager_1.autoLearnSoul)(workspaceRoot, topMemories);
1226
+ }
1227
+ // OpenClaw: Load access profile for personalized ranking
1228
+ (0, access_pattern_tracker_1.loadAccessProfile)(memoryStore);
1229
+ // OpenClaw: Auto-import user edits from MEMORY.md
1230
+ if (workspaceRoot) {
1231
+ try {
1232
+ const imported = (0, memory_export_md_1.importMemoryMd)(workspaceRoot, memoryStore);
1233
+ if (imported > 0)
1234
+ console.log(` [MEMORY.md] Imported ${imported} user-edited memories`);
1235
+ }
1236
+ catch { /* non-fatal */ }
1237
+ }
1211
1238
  }
1212
1239
  catch { /* maintenance errors are non-fatal */ }
1213
1240
  // ─── BRAIN LAYER 2: Attention Context ────────────────────────────
@@ -1265,6 +1292,15 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
1265
1292
  }
1266
1293
  return '';
1267
1294
  })(),
1295
+ // Layer 7.5: Daily Diary (OpenClaw-style)
1296
+ (async () => {
1297
+ try {
1298
+ return (0, daily_diary_1.formatDiaryContext)();
1299
+ }
1300
+ catch {
1301
+ return '';
1302
+ }
1303
+ })(),
1268
1304
  // Layer 8: Workspace State (git)
1269
1305
  (async () => {
1270
1306
  try {
@@ -1883,6 +1919,14 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
1883
1919
  });
1884
1920
  if (result.stored) {
1885
1921
  stored.push(`[${item.type}] ${item.content.slice(0, 60)}${item.content.length > 60 ? '…' : ''}`);
1922
+ // OpenClaw-style diary logging
1923
+ try {
1924
+ (0, daily_diary_1.appendDiaryEntry)({
1925
+ type: item.type.toLowerCase().replace('_', '_'),
1926
+ content: item.content.slice(0, 100),
1927
+ });
1928
+ }
1929
+ catch { /* diary is non-critical */ }
1886
1930
  }
1887
1931
  else {
1888
1932
  skipped.push(`[${item.type}] ${item.content.slice(0, 40)}… (duplicate)`);
@@ -1896,6 +1940,13 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
1896
1940
  (0, memory_cache_1.invalidateCache)();
1897
1941
  for (let i = 0; i < stored.length; i++)
1898
1942
  (0, usage_stats_1.trackStore)();
1943
+ // OpenClaw: Auto-export curated MEMORY.md after storing new memories
1944
+ if (workspaceRoot && stored.length >= 2) {
1945
+ try {
1946
+ (0, memory_export_md_1.generateMemoryMd)(memoryStore, workspaceRoot);
1947
+ }
1948
+ catch { /* non-fatal */ }
1949
+ }
1899
1950
  }
1900
1951
  // ─── Auto-correction capture ─────────────────────────────────────
1901
1952
  // Scan AI text for self-corrections ("I apologize", "you're right")
@@ -2112,6 +2163,10 @@ function createMCPHandler(memoryStore, eventLog, workspaceRoot) {
2112
2163
  `| Session Auto-Learn Count | ${stats.autoLearnCount}/500 |`,
2113
2164
  `| Session Total Calls | ${stats.totalCalls}/2000 |`,
2114
2165
  `| Uptime | ${Math.floor(stats.uptime / 60)}m ${stats.uptime % 60}s |`,
2166
+ `| Diary Days | ${(0, daily_diary_1.getDiaryStats)().totalDays} |`,
2167
+ `| Today's Diary Entries | ${(0, daily_diary_1.getDiaryStats)().todayEntries} |`,
2168
+ `| Top Memory Types | ${(0, access_pattern_tracker_1.getTopTypes)(3).map(t => `${t.type}(${t.count})`).join(', ') || 'none yet'} |`,
2169
+ `| Access Profile | ${(0, access_pattern_tracker_1.getAccessProfile)() ? 'loaded' : 'empty'} |`,
2115
2170
  `| Status | Healthy |`,
2116
2171
  ];
2117
2172
  return {