@causyne/agent 1.20.91 → 1.20.94

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 (46) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +116 -26
  3. package/src/agentLoop.ts +121 -26
  4. package/src/contextManager.js +2 -0
  5. package/src/decideTools.js +9 -0
  6. package/src/decideTools.ts +9 -0
  7. package/src/decisionPolicy.js +119 -1
  8. package/src/decisionPolicy.ts +129 -1
  9. package/src/historyPruner.js +16 -1
  10. package/src/historyPruner.ts +13 -1
  11. package/src/sandbox.js +33 -7
  12. package/src/skills/skillResourceSafety.js +70 -0
  13. package/src/skills/skillResourceSafety.ts +77 -0
  14. package/src/smartToolsUse.js +28 -11
  15. package/src/smartToolsUse.ts +34 -11
  16. package/src/taskShape.js +28 -13
  17. package/src/taskShape.ts +31 -12
  18. package/src/tools/codeSearcher.js +349 -210
  19. package/src/tools/codeSearcher.ts +408 -0
  20. package/src/tools/codebaseSearch.js +182 -68
  21. package/src/tools/codebaseSearch.ts +221 -0
  22. package/src/tools/deferredMcpSearch.js +94 -40
  23. package/src/tools/deferredMcpSearch.ts +89 -30
  24. package/src/tools/fsFind.js +180 -115
  25. package/src/tools/fsFind.ts +228 -0
  26. package/src/tools/fsList.js +149 -69
  27. package/src/tools/fsList.ts +224 -0
  28. package/src/tools/fsSearch.js +192 -189
  29. package/src/tools/fsSearch.ts +241 -0
  30. package/src/tools/readNativeSkill.js +34 -42
  31. package/src/tools/readNativeSkill.ts +38 -36
  32. package/src/tools/searchRelevance.js +70 -0
  33. package/src/tools/searchRelevance.ts +72 -0
  34. package/src/tools/toolSelfRepair.js +56 -20
  35. package/src/tools/toolSelfRepair.ts +58 -19
  36. package/src/tools/walkerSafety.js +445 -0
  37. package/src/tools/walkerSafety.ts +516 -0
  38. package/src/tui/composerGeometry.js +45 -0
  39. package/src/tui/composerGeometry.ts +80 -0
  40. package/src/tui/homeView.js +10 -6
  41. package/src/tui/homeView.ts +10 -6
  42. package/src/tui/lineEditor.js +8 -0
  43. package/src/tui/prompt.js +9 -4
  44. package/src/userSkills.js +183 -203
  45. package/src/userSkills.ts +301 -0
  46. package/src/userSkills.d.ts +0 -26
@@ -0,0 +1,221 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import {
4
+ MAX_FILE_BYTES,
5
+ checkSearchScope,
6
+ compileSafeSearchRegex,
7
+ createTraversalGuard,
8
+ isSafeSymlinkTarget,
9
+ looksBinaryFile,
10
+ resolveSearchRoot,
11
+ shouldExcludeChild,
12
+ type SearchExecutionContext,
13
+ type TraversalGuard
14
+ } from './walkerSafety.js';
15
+
16
+ const MAX_MATCHES = 50;
17
+
18
+ export interface CodebaseSearchArgs {
19
+ query: string;
20
+ target_directories?: string[] | undefined;
21
+ isRegex?: boolean | undefined;
22
+ }
23
+
24
+ export interface CodebaseSearchResult {
25
+ success: boolean;
26
+ output?: string;
27
+ error?: string;
28
+ aborted?: boolean;
29
+ }
30
+
31
+ async function* walkBounded(
32
+ dir: string,
33
+ rootReal: string,
34
+ seen: Set<string>,
35
+ guard: TraversalGuard,
36
+ depth: number,
37
+ context?: SearchExecutionContext
38
+ ): AsyncGenerator<string> {
39
+ if (!guard.enterDir(depth)) return;
40
+
41
+ let real: string;
42
+ try {
43
+ real = await fs.realpath(dir);
44
+ } catch {
45
+ return;
46
+ }
47
+ if (!isSafeSymlinkTarget(real, rootReal, context)) return;
48
+ if (seen.has(real)) return;
49
+ seen.add(real);
50
+
51
+ let entries;
52
+ try {
53
+ entries = await fs.readdir(dir, { withFileTypes: true });
54
+ } catch {
55
+ return;
56
+ }
57
+
58
+ for (const entry of entries) {
59
+ if (guard.checkStopped()) return;
60
+ if (shouldExcludeChild(real, entry.name)) continue;
61
+ const full = path.join(dir, entry.name);
62
+
63
+ if (entry.isDirectory()) {
64
+ yield* walkBounded(full, rootReal, seen, guard, depth + 1, context);
65
+ } else if (entry.isFile()) {
66
+ yield full;
67
+ } else if (entry.isSymbolicLink()) {
68
+ try {
69
+ const targetReal = await fs.realpath(full);
70
+ if (!isSafeSymlinkTarget(targetReal, rootReal, context)) continue;
71
+ const stat = await fs.stat(targetReal);
72
+ if (stat.isDirectory()) {
73
+ yield* walkBounded(targetReal, rootReal, seen, guard, depth + 1, context);
74
+ } else if (stat.isFile()) {
75
+ yield full;
76
+ }
77
+ } catch {
78
+ // Ignore broken symlinks.
79
+ }
80
+ }
81
+ }
82
+ }
83
+
84
+ export const codebaseSearch = {
85
+ schema: {
86
+ name: 'codebase_search',
87
+ description:
88
+ 'Find snippets of code safely across target workspace directories with bounded traversal and literal matching by default.',
89
+ parameters: {
90
+ type: 'object',
91
+ properties: {
92
+ query: { type: 'string', description: 'The search query to find relevant code.' },
93
+ target_directories: {
94
+ type: 'array',
95
+ items: { type: 'string' },
96
+ description: 'Directories or files to search'
97
+ },
98
+ isRegex: {
99
+ type: 'boolean',
100
+ description: 'Optional. Treat query as a regular expression (defaults to literal case-insensitive search).'
101
+ }
102
+ },
103
+ required: ['query'],
104
+ additionalProperties: false
105
+ }
106
+ },
107
+
108
+ async execute(
109
+ args: CodebaseSearchArgs,
110
+ context?: SearchExecutionContext
111
+ ): Promise<CodebaseSearchResult> {
112
+ try {
113
+ if (!args || typeof args.query !== 'string' || args.query.length === 0) {
114
+ return { success: false, error: 'Missing required "query" argument.' };
115
+ }
116
+
117
+ const compiled = compileSafeSearchRegex(args.query, {
118
+ isRegex: args.isRegex === true,
119
+ caseInsensitive: true
120
+ });
121
+ if (!compiled.regex) {
122
+ return { success: false, error: compiled.error || 'Invalid query pattern.' };
123
+ }
124
+ const regex = compiled.regex;
125
+
126
+ const dirs =
127
+ Array.isArray(args.target_directories) && args.target_directories.length > 0
128
+ ? args.target_directories
129
+ : ['.'];
130
+
131
+ const scopedRoots: Array<{ requested: string; realPath: string }> = [];
132
+ for (const dir of dirs) {
133
+ if (typeof dir !== 'string' || !dir.trim()) continue;
134
+ const candidate = resolveSearchRoot(dir, context);
135
+ const scope = checkSearchScope(candidate, context);
136
+ if (!scope.allowed || !scope.realPath) {
137
+ return {
138
+ success: false,
139
+ error: scope.error || `Target directory not allowed: ${dir}`
140
+ };
141
+ }
142
+ scopedRoots.push({ requested: candidate, realPath: scope.realPath });
143
+ }
144
+
145
+ if (scopedRoots.length === 0) {
146
+ const fallback = resolveSearchRoot('.', context);
147
+ const scope = checkSearchScope(fallback, context);
148
+ if (!scope.allowed || !scope.realPath) {
149
+ return { success: false, error: scope.error || `Target directory not allowed: ${fallback}` };
150
+ }
151
+ scopedRoots.push({ requested: fallback, realPath: scope.realPath });
152
+ }
153
+
154
+ const guard = createTraversalGuard({ signal: context?.signal });
155
+ const results: string[] = [];
156
+
157
+ const scanFile = async (file: string): Promise<void> => {
158
+ if (!guard.countFile()) return;
159
+ let stat;
160
+ try {
161
+ stat = await fs.stat(file);
162
+ } catch {
163
+ return;
164
+ }
165
+ if (stat.size > MAX_FILE_BYTES) return;
166
+ if (await looksBinaryFile(file)) return;
167
+
168
+ let content: string;
169
+ try {
170
+ content = await fs.readFile(file, 'utf8');
171
+ } catch {
172
+ return;
173
+ }
174
+
175
+ const lines = content.split('\n');
176
+ for (let i = 0; i < lines.length; i++) {
177
+ if (guard.checkStopped()) break;
178
+ const line = lines[i]!;
179
+ if (regex.test(line)) {
180
+ results.push(`${file}:${i + 1}:${line.trim().slice(0, 300)}`);
181
+ if (results.length >= MAX_MATCHES) break;
182
+ }
183
+ }
184
+ };
185
+
186
+ for (const root of scopedRoots) {
187
+ if (results.length >= MAX_MATCHES || guard.checkStopped()) break;
188
+ let stat;
189
+ try {
190
+ stat = await fs.stat(root.realPath);
191
+ } catch {
192
+ continue;
193
+ }
194
+ if (stat.isFile()) {
195
+ await scanFile(root.realPath);
196
+ continue;
197
+ }
198
+ const seen = new Set<string>();
199
+ for await (const file of walkBounded(root.realPath, root.realPath, seen, guard, 0, context)) {
200
+ if (results.length >= MAX_MATCHES || guard.checkStopped()) break;
201
+ await scanFile(file);
202
+ }
203
+ }
204
+
205
+ if (guard.stopReason === 'aborted') {
206
+ return { success: false, aborted: true, error: 'Codebase search aborted.' };
207
+ }
208
+
209
+ const stopSuffix = guard.stopReason ? `\n\n[${guard.stopNotice()}]` : '';
210
+ return {
211
+ success: true,
212
+ output:
213
+ results.length > 0
214
+ ? results.join('\n') + stopSuffix
215
+ : `No results found.${guard.stopReason ? ` (${guard.stopNotice()})` : ''}`
216
+ };
217
+ } catch (error: unknown) {
218
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
219
+ }
220
+ }
221
+ };
@@ -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
@@ -135,7 +170,15 @@ export const deferredMcpSearch = {
135
170
  },
136
171
  async execute(args, context = {}) {
137
172
  try {
138
- const query = String(args.query ?? args.q ?? args.search ?? args.description ?? args.pattern ?? '').trim();
173
+ const rawQueries = args.queries;
174
+ const joinedQueries = Array.isArray(rawQueries)
175
+ ? rawQueries.map((item) => String(item ?? '').trim()).filter(Boolean).join(' ')
176
+ : (typeof rawQueries === 'string' ? rawQueries : '');
177
+ const rawQuery = Array.isArray(args.query)
178
+ ? args.query.map((item) => String(item ?? '').trim()).filter(Boolean).join(' ')
179
+ : args.query;
180
+ const query = String(rawQuery ?? args.q ?? args.search ?? args.term ??
181
+ args.regex ?? args.description ?? args.pattern ?? joinedQueries ?? '').trim();
139
182
  if (query.length > MAX_TOOL_SEARCH_QUERY) {
140
183
  return { success: false, error: `Search query exceeds ${MAX_TOOL_SEARCH_QUERY} characters. Use a shorter capability description.` };
141
184
  }
@@ -168,25 +211,31 @@ export const deferredMcpSearch = {
168
211
  }
169
212
  const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
170
213
  const lower = query.toLowerCase();
171
- const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
214
+ const terms = queryTerms(query);
172
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);
173
219
  const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
174
220
  const scored = (exact ? [exact] : definitions)
175
- .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
176
- .filter(entry => entry.score > 0)
177
- .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))
178
224
  .slice(0, limit);
179
225
  if (scored.length === 0) {
180
226
  // Still search skills. "how do I structure a django migration" matches
181
227
  // no tool name and every relevant skill — returning "no tools matched"
182
228
  // and stopping was the whole reason a 40-entry catalogue had to sit in
183
229
  // the system prompt.
184
- const skillOnly = await searchSkills(terms, pattern);
230
+ const skillOnly = await searchSkills(terms, pattern, { allowFallback: true });
185
231
  if (skillOnly.length > 0) {
232
+ const canUnlockSkillReader = !isResidentTool('fs_read_skill') &&
233
+ definitions.some((definition) => definition.name === 'fs_read_skill');
186
234
  return {
187
235
  success: true,
188
- output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
189
- skillOnly.join('\n')
236
+ output: `No tools matched "${query}". Matching SKILLS — read one with fs_read_skill:\n` +
237
+ skillOnly.join('\n'),
238
+ ...(canUnlockSkillReader ? { _unlock_tools: ['fs_read_skill'], _unlock_packs: [] } : {})
190
239
  };
191
240
  }
192
241
  return {
@@ -216,13 +265,18 @@ export const deferredMcpSearch = {
216
265
  // request of every task, including a bare "hi". Retrieval replaces the
217
266
  // catalogue — but only because the retrieval exists, which it did not
218
267
  // before this change.
219
- const skillLines = await searchSkills(terms, pattern);
268
+ const skillLines = exact ? [] : await searchSkills(terms, pattern, { allowFallback: false });
220
269
  const parts = [];
221
270
  if (scored.length > 0) {
222
271
  parts.push(`Found ${scored.length} tool(s) for "${query}". Their full schemas are now loaded and callable on your next turn:\n` +
223
272
  lines.join('\n'));
224
273
  }
225
274
  if (skillLines.length > 0) {
275
+ if (!isResidentTool('fs_read_skill') &&
276
+ !unlockTools.includes('fs_read_skill') &&
277
+ definitions.some((definition) => definition.name === 'fs_read_skill')) {
278
+ unlockTools.push('fs_read_skill');
279
+ }
226
280
  parts.push(`\nMatching SKILLS — read one with fs_read_skill before you plan, do not guess syntax it covers:\n` +
227
281
  skillLines.join('\n'));
228
282
  }
@@ -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 {
@@ -141,7 +176,17 @@ export const deferredMcpSearch = {
141
176
 
142
177
  async execute(args: SearchArgs, context: SearchContext = {}): Promise<SearchResult> {
143
178
  try {
144
- const query = String(args.query ?? (args as any).q ?? (args as any).search ?? (args as any).description ?? (args as any).pattern ?? '').trim();
179
+ const rawQueries = (args as any).queries;
180
+ const joinedQueries = Array.isArray(rawQueries)
181
+ ? rawQueries.map((item) => String(item ?? '').trim()).filter(Boolean).join(' ')
182
+ : (typeof rawQueries === 'string' ? rawQueries : '');
183
+ const rawQuery = Array.isArray(args.query)
184
+ ? args.query.map((item) => String(item ?? '').trim()).filter(Boolean).join(' ')
185
+ : args.query;
186
+ const query = String(
187
+ rawQuery ?? (args as any).q ?? (args as any).search ?? (args as any).term ??
188
+ (args as any).regex ?? (args as any).description ?? (args as any).pattern ?? joinedQueries ?? ''
189
+ ).trim();
145
190
  if (query.length > MAX_TOOL_SEARCH_QUERY) {
146
191
  return { success: false, error: `Search query exceeds ${MAX_TOOL_SEARCH_QUERY} characters. Use a shorter capability description.` };
147
192
  }
@@ -177,14 +222,17 @@ export const deferredMcpSearch = {
177
222
 
178
223
  const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
179
224
  const lower = query.toLowerCase();
180
- const terms = lower.split(/[^a-z0-9_]+/).filter(t => t.length > 2);
225
+ const terms = queryTerms(query);
181
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);
182
230
 
183
231
  const exact = definitions.find(definition => definition.name.toLowerCase() === lower);
184
232
  const scored = (exact ? [exact] : definitions)
185
- .map(definition => ({ definition, score: scoreTool(definition, terms, pattern) }))
186
- .filter(entry => entry.score > 0)
187
- .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))
188
236
  .slice(0, limit);
189
237
 
190
238
  if (scored.length === 0) {
@@ -192,12 +240,16 @@ export const deferredMcpSearch = {
192
240
  // no tool name and every relevant skill — returning "no tools matched"
193
241
  // and stopping was the whole reason a 40-entry catalogue had to sit in
194
242
  // the system prompt.
195
- const skillOnly = await searchSkills(terms, pattern);
243
+ const skillOnly = await searchSkills(terms, pattern, { allowFallback: true });
196
244
  if (skillOnly.length > 0) {
245
+ const canUnlockSkillReader =
246
+ !isResidentTool('fs_read_skill') &&
247
+ definitions.some((definition) => definition.name === 'fs_read_skill');
197
248
  return {
198
249
  success: true,
199
- output: `No tools matched "${query}", but these SKILLS did — read one with fs_read_skill:\n` +
200
- skillOnly.join('\n')
250
+ output: `No tools matched "${query}". Matching SKILLS — read one with fs_read_skill:\n` +
251
+ skillOnly.join('\n'),
252
+ ...(canUnlockSkillReader ? { _unlock_tools: ['fs_read_skill'], _unlock_packs: [] } : {})
201
253
  };
202
254
  }
203
255
  return {
@@ -229,7 +281,7 @@ export const deferredMcpSearch = {
229
281
  // request of every task, including a bare "hi". Retrieval replaces the
230
282
  // catalogue — but only because the retrieval exists, which it did not
231
283
  // before this change.
232
- const skillLines = await searchSkills(terms, pattern);
284
+ const skillLines = exact ? [] : await searchSkills(terms, pattern, { allowFallback: false });
233
285
 
234
286
  const parts = [];
235
287
  if (scored.length > 0) {
@@ -239,6 +291,13 @@ export const deferredMcpSearch = {
239
291
  );
240
292
  }
241
293
  if (skillLines.length > 0) {
294
+ if (
295
+ !isResidentTool('fs_read_skill') &&
296
+ !unlockTools.includes('fs_read_skill') &&
297
+ definitions.some((definition) => definition.name === 'fs_read_skill')
298
+ ) {
299
+ unlockTools.push('fs_read_skill');
300
+ }
242
301
  parts.push(
243
302
  `\nMatching SKILLS — read one with fs_read_skill before you plan, do not guess syntax it covers:\n` +
244
303
  skillLines.join('\n')