@causyne/agent 1.20.93 → 1.20.95

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.
@@ -10,6 +10,7 @@ async function toolDefinitions() {
10
10
  import { buildToolsList } from '../toolsList.js';
11
11
  import { PACKS, PACK_NAMES, packForTool, isCoreTool, isResidentTool } from '../toolPacks.js';
12
12
  import { literalSearchPattern, formatSkillSearchLine, MAX_TOOL_SEARCH_QUERY } from '../skills/skillSearchSafety.js';
13
+ import { queryTerms, wordsOf, termMatches, requiredCoverage } from './searchRelevance.js';
13
14
  /** Max skills returned alongside the tool matches, so one search stays cheap. */
14
15
  const MAX_SKILL_HITS = 5;
15
16
  /**
@@ -21,7 +22,7 @@ const MAX_SKILL_HITS = 5;
21
22
  *
22
23
  * @returns {string[]} formatted lines, empty when nothing matched
23
24
  */
24
- async function searchSkills(terms, pattern) {
25
+ async function searchSkills(terms, pattern, options = {}) {
25
26
  // Imported lazily, not at module scope: registry.js imports THIS module, and
26
27
  // skillsManager pulls registry back in transitively — a static import here
27
28
  // closes the cycle and the whole tool registry fails to initialise. Same
@@ -35,73 +36,107 @@ async function searchSkills(terms, pattern) {
35
36
  return []; // a broken skill store must not take tool search down
36
37
  }
37
38
  const scored = [];
39
+ const minCoverage = requiredCoverage(terms.length);
38
40
  for (const skill of catalogue) {
39
- const haystack = `${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`.toLowerCase();
41
+ // Whole-word matching: a substring test let "kill" match every "skill"
42
+ // and "and" match every "android".
43
+ const titleWords = wordsOf(`${skill.id} ${skill.name}`);
44
+ const domainWords = wordsOf(skill.domain);
45
+ const allWords = wordsOf(`${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`);
40
46
  let score = 0;
47
+ let coverage = 0;
48
+ let phraseHit = false;
41
49
  if (pattern) {
42
- if (pattern.test(skill.name) || pattern.test(skill.id))
50
+ if (pattern.test(skill.name) || pattern.test(skill.id)) {
43
51
  score += 10;
52
+ phraseHit = true;
53
+ }
44
54
  if (pattern.test(skill.description || ''))
45
55
  score += 4;
46
56
  }
47
57
  for (const term of terms) {
48
- if (skill.id.toLowerCase().includes(term) || skill.name.toLowerCase().includes(term))
58
+ if (termMatches(term, titleWords)) {
49
59
  score += 8;
50
- else if (skill.domain.toLowerCase() === term)
60
+ coverage++;
61
+ }
62
+ else if (termMatches(term, domainWords)) {
51
63
  score += 6;
52
- else if (haystack.includes(term))
64
+ coverage++;
65
+ }
66
+ else if (termMatches(term, allWords)) {
53
67
  score += 3;
68
+ coverage++;
69
+ }
54
70
  }
55
71
  if (score > 0)
56
- scored.push({ skill, score });
72
+ scored.push({ skill, score, coverage, phraseHit });
57
73
  }
58
- return scored
59
- .sort((a, b) => b.score - a.score)
74
+ const strong = scored.filter(entry => entry.phraseHit || entry.coverage >= minCoverage);
75
+ const pool = strong.length > 0 ? strong : (options.allowFallback ? scored : []);
76
+ return pool
77
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
60
78
  .slice(0, MAX_SKILL_HITS)
61
79
  .map(({ skill }) => formatSkillSearchLine(skill));
62
80
  }
63
- // Real progressive-disclosure tool search.
64
- //
65
- // The previous version of this file advertised "80% token savings" while
66
- // searching a hardcoded catalogue of seven tools that did not exist in the
67
- // registry (mcp_postgres_data, mcp_github_workflow, mcp_android_cli). Any tool
68
- // the model discovered that way led straight to a "Tool does not exist" error,
69
- // and nothing was ever actually deferred.
70
- //
71
- // This version searches the live tool registry and unlocks what it finds. The
72
- // agent loop reads the _unlock_* fields off the result and loads the matching
73
- // schemas into the next request.
74
81
  function scoreTool(definition, terms, pattern) {
75
82
  const name = (definition.name || '').toLowerCase();
76
83
  const description = (definition.description || '').toLowerCase();
77
- // Parameter names and descriptions are searchable too — a query like
78
- // "kill process on port" should find a tool whose `port` argument mentions it.
79
- let parameterText = '';
84
+ // Parameter names (e.g. `port`) identify capabilities directly; parameter
85
+ // descriptions often list example platforms and act only as tiebreakers.
86
+ let paramKeysText = '';
87
+ let paramDescText = '';
80
88
  const properties = definition.parameters?.properties || definition.input_schema?.properties;
81
89
  if (properties) {
82
90
  for (const [key, value] of Object.entries(properties)) {
83
- parameterText += ` ${key} ${(value && value.description) || ''}`;
91
+ paramKeysText += ` ${key}`;
92
+ if (value && value.description) {
93
+ paramDescText += ` ${value.description}`;
94
+ }
84
95
  }
85
96
  }
86
- parameterText = parameterText.toLowerCase();
97
+ paramKeysText = paramKeysText.toLowerCase();
98
+ paramDescText = paramDescText.toLowerCase();
87
99
  let score = 0;
100
+ let coverage = 0;
101
+ let nameHit = false;
88
102
  if (pattern) {
89
- if (pattern.test(name))
103
+ if (pattern.test(name)) {
90
104
  score += 12;
105
+ nameHit = true;
106
+ }
91
107
  if (pattern.test(description))
92
108
  score += 6;
93
- if (pattern.test(parameterText))
109
+ if (pattern.test(paramKeysText) || pattern.test(paramDescText))
94
110
  score += 2;
95
111
  }
112
+ // Whole-word matching. Substring tests let "and" hit "command", "kill" hit
113
+ // "skill" and "port" hit "export", which unlocked unrelated schemas.
114
+ const nameWords = wordsOf(definition.name || '');
115
+ const descriptionWords = wordsOf(description);
116
+ const paramKeyWords = wordsOf(paramKeysText);
117
+ const paramDescWords = wordsOf(paramDescText);
96
118
  for (const term of terms) {
97
- if (name.includes(term))
119
+ let matched = false;
120
+ if (termMatches(term, nameWords)) {
98
121
  score += 10;
99
- if (description.includes(term))
122
+ matched = true;
123
+ }
124
+ if (termMatches(term, descriptionWords)) {
100
125
  score += 4;
101
- if (parameterText.includes(term))
126
+ matched = true;
127
+ }
128
+ if (termMatches(term, paramKeyWords)) {
129
+ score += 3;
130
+ matched = true;
131
+ }
132
+ if (matched) {
133
+ coverage++;
134
+ }
135
+ else if (termMatches(term, paramDescWords)) {
102
136
  score += 1;
137
+ }
103
138
  }
104
- return score;
139
+ return { score, coverage, nameHit };
105
140
  }
106
141
  function buildPattern(query) {
107
142
  // Never compile LLM-generated regex. A pattern such as (a+)+$ can freeze
@@ -176,26 +211,29 @@ export const deferredMcpSearch = {
176
211
  }
177
212
  const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
178
213
  const lower = query.toLowerCase();
179
- const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
214
+ const terms = queryTerms(query);
180
215
  const pattern = buildPattern(query);
216
+ // Tool discovery stays bounded: an entry sharing a single generic word
217
+ // with a multi-word request is not a match.
218
+ const minCoverage = requiredCoverage(terms.length);
181
219
  const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
182
220
  const scored = (exact ? [exact] : definitions)
183
- .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
184
- .filter(entry => entry.score > 0)
185
- .sort((a, b) => b.score - a.score)
221
+ .map(definition => ({ definition, ...scoreTool(definition, terms, pattern) }))
222
+ .filter(entry => entry.score > 0 && (exact !== undefined || entry.nameHit || entry.coverage >= minCoverage))
223
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
186
224
  .slice(0, limit);
187
225
  if (scored.length === 0) {
188
226
  // Still search skills. "how do I structure a django migration" matches
189
227
  // no tool name and every relevant skill — returning "no tools matched"
190
228
  // and stopping was the whole reason a 40-entry catalogue had to sit in
191
229
  // the system prompt.
192
- const skillOnly = await searchSkills(terms, pattern);
230
+ const skillOnly = await searchSkills(terms, pattern, { allowFallback: true });
193
231
  if (skillOnly.length > 0) {
194
232
  const canUnlockSkillReader = !isResidentTool('fs_read_skill') &&
195
233
  definitions.some((definition) => definition.name === 'fs_read_skill');
196
234
  return {
197
235
  success: true,
198
- output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
236
+ output: `No tools matched "${query}". Matching SKILLS — read one with fs_read_skill:\n` +
199
237
  skillOnly.join('\n'),
200
238
  ...(canUnlockSkillReader ? { _unlock_tools: ['fs_read_skill'], _unlock_packs: [] } : {})
201
239
  };
@@ -227,7 +265,7 @@ export const deferredMcpSearch = {
227
265
  // request of every task, including a bare "hi". Retrieval replaces the
228
266
  // catalogue — but only because the retrieval exists, which it did not
229
267
  // before this change.
230
- const skillLines = await searchSkills(terms, pattern);
268
+ const skillLines = exact ? [] : await searchSkills(terms, pattern, { allowFallback: false });
231
269
  const parts = [];
232
270
  if (scored.length > 0) {
233
271
  parts.push(`Found ${scored.length} tool(s) for "${query}". Their full schemas are now loaded and callable on your next turn:\n` +
@@ -15,6 +15,7 @@ async function toolDefinitions(): Promise<ToolDefinition[]> {
15
15
  import { buildToolsList } from '../toolsList.js';
16
16
  import { PACKS, PACK_NAMES, packForTool, isCoreTool, isResidentTool } from '../toolPacks.js';
17
17
  import { literalSearchPattern, formatSkillSearchLine, MAX_TOOL_SEARCH_QUERY } from '../skills/skillSearchSafety.js';
18
+ import { queryTerms, wordsOf, termMatches, requiredCoverage } from './searchRelevance.js';
18
19
 
19
20
  /** Max skills returned alongside the tool matches, so one search stays cheap. */
20
21
  const MAX_SKILL_HITS = 5;
@@ -28,7 +29,11 @@ const MAX_SKILL_HITS = 5;
28
29
  *
29
30
  * @returns {string[]} formatted lines, empty when nothing matched
30
31
  */
31
- async function searchSkills(terms: string[], pattern: RegExp | null): Promise<string[]> {
32
+ async function searchSkills(
33
+ terms: string[],
34
+ pattern: RegExp | null,
35
+ options: { allowFallback?: boolean } = {}
36
+ ): Promise<string[]> {
32
37
  // Imported lazily, not at module scope: registry.js imports THIS module, and
33
38
  // skillsManager pulls registry back in transitively — a static import here
34
39
  // closes the cycle and the whole tool registry fails to initialise. Same
@@ -42,23 +47,32 @@ async function searchSkills(terms: string[], pattern: RegExp | null): Promise<st
42
47
  }
43
48
 
44
49
  const scored = [];
50
+ const minCoverage = requiredCoverage(terms.length);
45
51
  for (const skill of catalogue) {
46
- const haystack = `${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`.toLowerCase();
52
+ // Whole-word matching: a substring test let "kill" match every "skill"
53
+ // and "and" match every "android".
54
+ const titleWords = wordsOf(`${skill.id} ${skill.name}`);
55
+ const domainWords = wordsOf(skill.domain);
56
+ const allWords = wordsOf(`${skill.id} ${skill.name} ${skill.domain} ${skill.description || ''}`);
47
57
  let score = 0;
58
+ let coverage = 0;
59
+ let phraseHit = false;
48
60
  if (pattern) {
49
- if (pattern.test(skill.name) || pattern.test(skill.id)) score += 10;
61
+ if (pattern.test(skill.name) || pattern.test(skill.id)) { score += 10; phraseHit = true; }
50
62
  if (pattern.test(skill.description || '')) score += 4;
51
63
  }
52
64
  for (const term of terms) {
53
- if (skill.id.toLowerCase().includes(term) || skill.name.toLowerCase().includes(term)) score += 8;
54
- else if (skill.domain.toLowerCase() === term) score += 6;
55
- else if (haystack.includes(term)) score += 3;
65
+ if (termMatches(term, titleWords)) { score += 8; coverage++; }
66
+ else if (termMatches(term, domainWords)) { score += 6; coverage++; }
67
+ else if (termMatches(term, allWords)) { score += 3; coverage++; }
56
68
  }
57
- if (score > 0) scored.push({ skill, score });
69
+ if (score > 0) scored.push({ skill, score, coverage, phraseHit });
58
70
  }
59
71
 
60
- return scored
61
- .sort((a, b) => b.score - a.score)
72
+ const strong = scored.filter(entry => entry.phraseHit || entry.coverage >= minCoverage);
73
+ const pool = strong.length > 0 ? strong : (options.allowFallback ? scored : []);
74
+ return pool
75
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
62
76
  .slice(0, MAX_SKILL_HITS)
63
77
  .map(({ skill }) => formatSkillSearchLine(skill));
64
78
  }
@@ -75,36 +89,57 @@ async function searchSkills(terms: string[], pattern: RegExp | null): Promise<st
75
89
  // agent loop reads the _unlock_* fields off the result and loads the matching
76
90
  // schemas into the next request.
77
91
 
78
- function scoreTool(definition: ToolDefinition, terms: string[], pattern: RegExp | null): number {
92
+ interface ToolScore { score: number; coverage: number; nameHit: boolean; }
93
+
94
+ function scoreTool(definition: ToolDefinition, terms: string[], pattern: RegExp | null): ToolScore {
79
95
  const name = (definition.name || '').toLowerCase();
80
96
  const description = (definition.description || '').toLowerCase();
81
97
 
82
- // Parameter names and descriptions are searchable too — a query like
83
- // "kill process on port" should find a tool whose `port` argument mentions it.
84
- let parameterText = '';
98
+ // Parameter names (e.g. `port`) identify capabilities directly; parameter
99
+ // descriptions often list example platforms and act only as tiebreakers.
100
+ let paramKeysText = '';
101
+ let paramDescText = '';
85
102
  const properties = definition.parameters?.properties || definition.input_schema?.properties;
86
103
  if (properties) {
87
104
  for (const [key, value] of Object.entries(properties)) {
88
- parameterText += ` ${key} ${(value && value.description) || ''}`;
105
+ paramKeysText += ` ${key}`;
106
+ if (value && value.description) {
107
+ paramDescText += ` ${value.description}`;
108
+ }
89
109
  }
90
110
  }
91
- parameterText = parameterText.toLowerCase();
111
+ paramKeysText = paramKeysText.toLowerCase();
112
+ paramDescText = paramDescText.toLowerCase();
92
113
 
93
114
  let score = 0;
115
+ let coverage = 0;
116
+ let nameHit = false;
94
117
 
95
118
  if (pattern) {
96
- if (pattern.test(name)) score += 12;
119
+ if (pattern.test(name)) { score += 12; nameHit = true; }
97
120
  if (pattern.test(description)) score += 6;
98
- if (pattern.test(parameterText)) score += 2;
121
+ if (pattern.test(paramKeysText) || pattern.test(paramDescText)) score += 2;
99
122
  }
100
123
 
124
+ // Whole-word matching. Substring tests let "and" hit "command", "kill" hit
125
+ // "skill" and "port" hit "export", which unlocked unrelated schemas.
126
+ const nameWords = wordsOf(definition.name || '');
127
+ const descriptionWords = wordsOf(description);
128
+ const paramKeyWords = wordsOf(paramKeysText);
129
+ const paramDescWords = wordsOf(paramDescText);
101
130
  for (const term of terms) {
102
- if (name.includes(term)) score += 10;
103
- if (description.includes(term)) score += 4;
104
- if (parameterText.includes(term)) score += 1;
131
+ let matched = false;
132
+ if (termMatches(term, nameWords)) { score += 10; matched = true; }
133
+ if (termMatches(term, descriptionWords)) { score += 4; matched = true; }
134
+ if (termMatches(term, paramKeyWords)) { score += 3; matched = true; }
135
+ if (matched) {
136
+ coverage++;
137
+ } else if (termMatches(term, paramDescWords)) {
138
+ score += 1;
139
+ }
105
140
  }
106
141
 
107
- return score;
142
+ return { score, coverage, nameHit };
108
143
  }
109
144
 
110
145
  function buildPattern(query: string): RegExp | null {
@@ -187,14 +222,17 @@ export const deferredMcpSearch = {
187
222
 
188
223
  const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
189
224
  const lower = query.toLowerCase();
190
- const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
225
+ const terms = queryTerms(query);
191
226
  const pattern = buildPattern(query);
227
+ // Tool discovery stays bounded: an entry sharing a single generic word
228
+ // with a multi-word request is not a match.
229
+ const minCoverage = requiredCoverage(terms.length);
192
230
 
193
231
  const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
194
232
  const scored = (exact ? [exact] : definitions)
195
- .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
196
- .filter(entry => entry.score > 0)
197
- .sort((a, b) => b.score - a.score)
233
+ .map(definition => ({ definition, ...scoreTool(definition, terms, pattern) }))
234
+ .filter(entry => entry.score > 0 && (exact !== undefined || entry.nameHit || entry.coverage >= minCoverage))
235
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
198
236
  .slice(0, limit);
199
237
 
200
238
  if (scored.length === 0) {
@@ -202,14 +240,14 @@ export const deferredMcpSearch = {
202
240
  // no tool name and every relevant skill — returning "no tools matched"
203
241
  // and stopping was the whole reason a 40-entry catalogue had to sit in
204
242
  // the system prompt.
205
- const skillOnly = await searchSkills(terms, pattern);
243
+ const skillOnly = await searchSkills(terms, pattern, { allowFallback: true });
206
244
  if (skillOnly.length > 0) {
207
245
  const canUnlockSkillReader =
208
246
  !isResidentTool('fs_read_skill') &&
209
247
  definitions.some((definition) => definition.name === 'fs_read_skill');
210
248
  return {
211
249
  success: true,
212
- output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
250
+ output: `No tools matched "${query}". Matching SKILLS — read one with fs_read_skill:\n` +
213
251
  skillOnly.join('\n'),
214
252
  ...(canUnlockSkillReader ? { _unlock_tools: ['fs_read_skill'], _unlock_packs: [] } : {})
215
253
  };
@@ -243,7 +281,7 @@ export const deferredMcpSearch = {
243
281
  // request of every task, including a bare "hi". Retrieval replaces the
244
282
  // catalogue — but only because the retrieval exists, which it did not
245
283
  // before this change.
246
- const skillLines = await searchSkills(terms, pattern);
284
+ const skillLines = exact ? [] : await searchSkills(terms, pattern, { allowFallback: false });
247
285
 
248
286
  const parts = [];
249
287
  if (scored.length > 0) {
@@ -9,6 +9,38 @@
9
9
  import { listCompiledSkills, readCompiledSkill } from '../skillsManager.js';
10
10
  import { parseSkillId, userSkillsRoot } from '../userSkills.js';
11
11
  import { listSkillResourcePaths, readSkillTextResource } from '../skills/skillResourceSafety.js';
12
+ import { queryTerms, wordsOf, termMatches, requiredCoverage } from './searchRelevance.js';
13
+ function suggestSimilarSkills(allSkills, seed, limit = 3) {
14
+ const terms = queryTerms(seed);
15
+ if (terms.length === 0)
16
+ return [];
17
+ const minCoverage = requiredCoverage(terms.length);
18
+ const ranked = allSkills
19
+ .map((skill) => {
20
+ const titleWords = wordsOf(`${skill.domain} ${skill.id} ${skill.name || ''}`);
21
+ const descWords = wordsOf(skill.description || '');
22
+ let score = 0;
23
+ let coverage = 0;
24
+ for (const term of terms) {
25
+ if (termMatches(term, titleWords)) {
26
+ score += 10;
27
+ coverage += 1;
28
+ }
29
+ else if (termMatches(term, descWords)) {
30
+ score += 3;
31
+ coverage += 1;
32
+ }
33
+ }
34
+ return { skill, score, coverage };
35
+ })
36
+ .filter((entry) => entry.score > 0);
37
+ const strong = ranked.filter((entry) => entry.coverage >= minCoverage);
38
+ const pool = strong.length > 0 ? strong : ranked;
39
+ return pool
40
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
41
+ .slice(0, limit)
42
+ .map((entry) => `${entry.skill.domain}/${entry.skill.id}`);
43
+ }
12
44
  export default {
13
45
  schema: {
14
46
  name: 'fs_read_skill',
@@ -47,27 +79,7 @@ export default {
47
79
  id = directMatch.id;
48
80
  }
49
81
  else if ('error' in parsed) {
50
- const queryTokens = rawSkillId.toLowerCase().split(/[\/_-]/).filter(t => t.length > 2);
51
- const suggestions = allSkills
52
- .map(s => {
53
- let score = 0;
54
- const d = s.domain.toLowerCase();
55
- const n = s.id.toLowerCase();
56
- const desc = (s.description || '').toLowerCase();
57
- for (const t of queryTokens) {
58
- if (n.includes(t))
59
- score += 10;
60
- if (d.includes(t))
61
- score += 8;
62
- if (desc.includes(t))
63
- score += 2;
64
- }
65
- return { skill: s, score };
66
- })
67
- .filter(item => item.score > 0)
68
- .sort((a, b) => b.score - a.score)
69
- .slice(0, 3)
70
- .map(item => `${item.skill.domain}/${item.skill.id}`);
82
+ const suggestions = suggestSimilarSkills(allSkills, rawSkillId);
71
83
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
72
84
  return { success: false, error: `Invalid skill id "${rawSkillId}".${hint} Expected "domain/name", for example android/gradle-build-configuration.` };
73
85
  }
@@ -82,27 +94,7 @@ export default {
82
94
  }
83
95
  }
84
96
  if (!info) {
85
- const queryTokens = `${domain || ''} ${id || ''} ${rawSkillId}`.toLowerCase().split(/[\/_-]/).filter(t => t.length > 2);
86
- const suggestions = allSkills
87
- .map(s => {
88
- let score = 0;
89
- const d = s.domain.toLowerCase();
90
- const n = s.id.toLowerCase();
91
- const desc = (s.description || '').toLowerCase();
92
- for (const t of queryTokens) {
93
- if (n.includes(t))
94
- score += 10;
95
- if (d.includes(t))
96
- score += 8;
97
- if (desc.includes(t))
98
- score += 2;
99
- }
100
- return { skill: s, score };
101
- })
102
- .filter(item => item.score > 0)
103
- .sort((a, b) => b.score - a.score)
104
- .slice(0, 3)
105
- .map(item => `${item.skill.domain}/${item.skill.id}`);
97
+ const suggestions = suggestSimilarSkills(allSkills, `${domain || ''} ${id || ''} ${rawSkillId}`);
106
98
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
107
99
  return { success: false, error: `Unknown skill ${domain ? `${domain}/${id}` : rawSkillId}.${hint} Search the current catalog with tool_search first.` };
108
100
  }
@@ -9,6 +9,7 @@
9
9
  import { listCompiledSkills, readCompiledSkill } from '../skillsManager.js';
10
10
  import { parseSkillId, userSkillsRoot } from '../userSkills.js';
11
11
  import { listSkillResourcePaths, readSkillTextResource } from '../skills/skillResourceSafety.js';
12
+ import { queryTerms, wordsOf, termMatches, requiredCoverage } from './searchRelevance.js';
12
13
 
13
14
  interface SkillReadArgs {
14
15
  skill_id?: string;
@@ -19,6 +20,41 @@ interface SkillReadArgs {
19
20
  }
20
21
  interface SkillReadResult { success: boolean; result?: string; error?: string; }
21
22
 
23
+ function suggestSimilarSkills(
24
+ allSkills: ReturnType<typeof listCompiledSkills>,
25
+ seed: string,
26
+ limit = 3
27
+ ): string[] {
28
+ const terms = queryTerms(seed);
29
+ if (terms.length === 0) return [];
30
+ const minCoverage = requiredCoverage(terms.length);
31
+ const ranked = allSkills
32
+ .map((skill) => {
33
+ const titleWords = wordsOf(`${skill.domain} ${skill.id} ${skill.name || ''}`);
34
+ const descWords = wordsOf(skill.description || '');
35
+ let score = 0;
36
+ let coverage = 0;
37
+ for (const term of terms) {
38
+ if (termMatches(term, titleWords)) {
39
+ score += 10;
40
+ coverage += 1;
41
+ } else if (termMatches(term, descWords)) {
42
+ score += 3;
43
+ coverage += 1;
44
+ }
45
+ }
46
+ return { skill, score, coverage };
47
+ })
48
+ .filter((entry) => entry.score > 0);
49
+
50
+ const strong = ranked.filter((entry) => entry.coverage >= minCoverage);
51
+ const pool = strong.length > 0 ? strong : ranked;
52
+ return pool
53
+ .sort((a, b) => (b.coverage - a.coverage) || (b.score - a.score))
54
+ .slice(0, limit)
55
+ .map((entry) => `${entry.skill.domain}/${entry.skill.id}`);
56
+ }
57
+
22
58
  export default {
23
59
  schema: {
24
60
  name: 'fs_read_skill',
@@ -57,24 +93,7 @@ export default {
57
93
  domain = directMatch.domain;
58
94
  id = directMatch.id;
59
95
  } else if ('error' in parsed) {
60
- const queryTokens = rawSkillId.toLowerCase().split(/[\/_-]/).filter(t => t.length > 2);
61
- const suggestions = allSkills
62
- .map(s => {
63
- let score = 0;
64
- const d = s.domain.toLowerCase();
65
- const n = s.id.toLowerCase();
66
- const desc = (s.description || '').toLowerCase();
67
- for (const t of queryTokens) {
68
- if (n.includes(t)) score += 10;
69
- if (d.includes(t)) score += 8;
70
- if (desc.includes(t)) score += 2;
71
- }
72
- return { skill: s, score };
73
- })
74
- .filter(item => item.score > 0)
75
- .sort((a, b) => b.score - a.score)
76
- .slice(0, 3)
77
- .map(item => `${item.skill.domain}/${item.skill.id}`);
96
+ const suggestions = suggestSimilarSkills(allSkills, rawSkillId);
78
97
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
79
98
  return { success: false, error: `Invalid skill id "${rawSkillId}".${hint} Expected "domain/name", for example android/gradle-build-configuration.` };
80
99
  }
@@ -91,24 +110,7 @@ export default {
91
110
  }
92
111
 
93
112
  if (!info) {
94
- const queryTokens = `${domain || ''} ${id || ''} ${rawSkillId}`.toLowerCase().split(/[\/_-]/).filter(t => t.length > 2);
95
- const suggestions = allSkills
96
- .map(s => {
97
- let score = 0;
98
- const d = s.domain.toLowerCase();
99
- const n = s.id.toLowerCase();
100
- const desc = (s.description || '').toLowerCase();
101
- for (const t of queryTokens) {
102
- if (n.includes(t)) score += 10;
103
- if (d.includes(t)) score += 8;
104
- if (desc.includes(t)) score += 2;
105
- }
106
- return { skill: s, score };
107
- })
108
- .filter(item => item.score > 0)
109
- .sort((a, b) => b.score - a.score)
110
- .slice(0, 3)
111
- .map(item => `${item.skill.domain}/${item.skill.id}`);
113
+ const suggestions = suggestSimilarSkills(allSkills, `${domain || ''} ${id || ''} ${rawSkillId}`);
112
114
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
113
115
  return { success: false, error: `Unknown skill ${domain ? `${domain}/${id}` : rawSkillId}.${hint} Search the current catalog with tool_search first.` };
114
116
  }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Causyne Agent — word-level relevance for tool and skill discovery.
3
+ *
4
+ * Substring matching made short query words hit unrelated entries ("and"
5
+ * inside "command", "kill" inside "skill", "git" inside "digit"), so one
6
+ * capability search could unlock a dozen irrelevant tool schemas. Matching is
7
+ * done on whole words with a bounded prefix rule instead. Deterministic,
8
+ * synchronous, linear-time, and never compiles user-supplied patterns.
9
+ */
10
+ /** English function words and search meta-words that carry no capability signal. */
11
+ const STOPWORDS = new Set([
12
+ 'and', 'the', 'for', 'with', 'from', 'into', 'onto', 'that', 'this', 'these', 'those',
13
+ 'using', 'use', 'via', 'any', 'all', 'are', 'was', 'were', 'can', 'how', 'what', 'which',
14
+ 'when', 'where', 'who', 'why', 'you', 'your', 'our', 'its', 'not', 'but', 'has', 'have',
15
+ 'should', 'would', 'could', 'please', 'about', 'also', 'then', 'than', 'them', 'they',
16
+ 'there', 'some', 'more', 'most', 'each', 'other', 'only', 'own', 'same', 'such', 'very',
17
+ 'just', 'like', 'need', 'want', 'help', 'let', 'get', 'take', 'out', 'over', 'under', 'per',
18
+ 'capability', 'capabilities', 'matching'
19
+ ]);
20
+ /** Upper bound on distinct query terms, so scoring cost stays constant. */
21
+ export const MAX_RELEVANCE_TERMS = 16;
22
+ /**
23
+ * Lower-case text and fold British -ise/-isation spellings onto -ize/-ization
24
+ * so "optimisation" and "optimization" compare equal. Applied identically to
25
+ * queries and catalog text.
26
+ */
27
+ export function normalizeSpelling(text) {
28
+ return text.toLowerCase().replace(/is(ations?|ing|ed|es|e)\b/g, 'iz$1');
29
+ }
30
+ /** Distinct meaningful query terms: alphanumeric words longer than two characters. */
31
+ export function queryTerms(query) {
32
+ const terms = [];
33
+ for (const word of normalizeSpelling(String(query || '')).split(/[^a-z0-9]+/)) {
34
+ if (word.length <= 2 || STOPWORDS.has(word) || terms.includes(word))
35
+ continue;
36
+ terms.push(word);
37
+ if (terms.length >= MAX_RELEVANCE_TERMS)
38
+ break;
39
+ }
40
+ return terms;
41
+ }
42
+ /** Whole words of catalog text, splitting snake_case, kebab-case and camelCase names. */
43
+ export function wordsOf(text) {
44
+ const spaced = String(text || '').replace(/([a-z0-9])([A-Z])/g, '$1 $2');
45
+ return new Set(normalizeSpelling(spaced).split(/[^a-z0-9]+/).filter(word => word.length > 0));
46
+ }
47
+ /**
48
+ * A term matches a word exactly, or as a bounded stem: "build" matches
49
+ * "builds"/"builder", and "screenshots" matches "screenshot". Short words
50
+ * never match as a fragment of a longer one.
51
+ */
52
+ export function termMatches(term, words) {
53
+ if (words.has(term))
54
+ return true;
55
+ for (const word of words) {
56
+ if (term.length >= 4 && word.startsWith(term))
57
+ return true;
58
+ if (word.length >= 4 && term.startsWith(word) && term.length - word.length <= 3)
59
+ return true;
60
+ }
61
+ return false;
62
+ }
63
+ /**
64
+ * Minimum number of distinct query terms an entry must match. A multi-word
65
+ * capability description is not satisfied by an entry that shares only one
66
+ * generic word with it (for example "build" in "android build optimization").
67
+ */
68
+ export function requiredCoverage(termCount) {
69
+ return termCount >= 3 ? 2 : 1;
70
+ }