@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
@@ -1,198 +1,201 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
3
-
4
- // Text search across a directory tree.
5
- //
6
- // The previous implementation had four problems that only show up on a real
7
- // repository (finding D-13):
8
- //
9
- // 1. It recursed without tracking realpaths, so a symlink pointing at an
10
- // ancestor sent it round forever.
11
- // 2. It read every candidate file whole into memory with no size cap — one
12
-
13
- // 3. It decided "binary" from a fixed list of nine extensions, so `.woff2`,
14
- // `.mp4`, `.class`, `.pdf` and every unknown format were parsed as text.
15
- // 4. It excluded exactly five directory names, ignoring `.gitignore`, so it
16
- // spent most of its time inside build output the user never wanted.
17
- //
18
- // And when it found nothing it said "No matches found. (Semantic Search module
19
- // pending activation)" — advertising a module that was two comment lines. That
20
- // sentence is gone: the tool now reports only what it actually did.
21
-
22
- const DEFAULT_EXCLUDES = [
23
- 'node_modules', '.git', '.hg', '.svn', 'dist', 'build', 'out', 'target',
24
- '.gradle', '.idea', '.vscode', '.next', '.nuxt', '.cache', '__pycache__',
25
- 'venv', '.venv', 'vendor', 'Pods', 'DerivedData', 'coverage', '.terraform'
26
- ];
27
-
28
- // Above this, a file is treated as data rather than source. Large minified
29
- // bundles and lockfiles are the common case and are rarely what a search is for.
30
- const MAX_FILE_BYTES = 2 * 1024 * 1024;
31
-
32
- // A NUL byte in the first block is the standard binary heuristic — the same one
33
- // grep uses. It is content-based, so it works for formats nobody listed.
34
- const SNIFF_BYTES = 8192;
35
-
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { MAX_FILE_BYTES, checkSearchScope, compileSafeSearchRegex, createTraversalGuard, isSafeSymlinkTarget, loadGitIgnoreNames, looksBinaryFile, resolveSearchRoot, shouldExcludeChild } from './walkerSafety.js';
36
4
  const DEFAULT_MAX_RESULTS = 100;
37
-
38
- /** Turn a .gitignore into a matcher. Deliberately simple: names and globs. */
39
- async function loadIgnorePatterns(root) {
40
- const patterns = [];
41
- try {
42
- const raw = await fs.readFile(path.join(root, '.gitignore'), 'utf8');
43
- for (const line of raw.split('\n')) {
44
- const trimmed = line.trim();
45
- if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('!')) continue;
46
- patterns.push(trimmed.replace(/^\/+|\/+$/g, ''));
5
+ async function* walk(dir, rootReal, ignorePatterns, seen, guard, depth, context) {
6
+ if (!guard.enterDir(depth))
7
+ return;
8
+ let real;
9
+ try {
10
+ real = await fs.realpath(dir);
47
11
  }
48
- } catch (e) { /* no .gitignore is the normal case outside a repo */ }
49
- return patterns;
50
- }
51
-
52
- function isIgnored(name, patterns) {
53
- for (const pattern of patterns) {
54
- if (pattern === name) return true;
55
- // Only the two glob shapes that actually appear in most .gitignore files.
56
- if (pattern.startsWith('*') && name.endsWith(pattern.slice(1))) return true;
57
- if (pattern.endsWith('*') && name.startsWith(pattern.slice(0, -1))) return true;
58
- }
59
- return false;
60
- }
61
-
62
- /**
63
- * Walk a tree, yielding file paths.
64
- *
65
- * `seen` holds the realpath of every directory already entered, which is what
66
- * stops a symlink cycle: `a/link -> ..` resolves to a directory already in the
67
- * set and is skipped rather than followed forever.
68
- */
69
- async function* walk(dir, excludes, ignorePatterns, seen) {
70
- let real;
71
- try {
72
- real = await fs.realpath(dir);
73
- } catch (e) {
74
- return;
75
- }
76
- if (seen.has(real)) return;
77
- seen.add(real);
78
-
79
- let entries;
80
- try {
81
- entries = await fs.readdir(dir, { withFileTypes: true });
82
- } catch (e) {
83
- return; // unreadable directory: skip it, do not fail the whole search
84
- }
85
-
86
- for (const entry of entries) {
87
- if (excludes.includes(entry.name) || isIgnored(entry.name, ignorePatterns)) continue;
88
- const full = path.join(dir, entry.name);
89
- if (entry.isDirectory()) {
90
- yield* walk(full, excludes, ignorePatterns, seen);
91
- } else if (entry.isFile()) {
92
- yield full;
93
- } else if (entry.isSymbolicLink()) {
94
- // Resolve once and classify; the `seen` set handles a directory cycle.
95
- try {
96
- const stat = await fs.stat(full);
97
- if (stat.isDirectory()) yield* walk(full, excludes, ignorePatterns, seen);
98
- else if (stat.isFile()) yield full;
99
- } catch (e) { /* broken link */ }
12
+ catch {
13
+ return;
14
+ }
15
+ if (!isSafeSymlinkTarget(real, rootReal, context))
16
+ return;
17
+ if (seen.has(real))
18
+ return;
19
+ seen.add(real);
20
+ let entries;
21
+ try {
22
+ entries = await fs.readdir(dir, { withFileTypes: true });
23
+ }
24
+ catch {
25
+ return;
26
+ }
27
+ for (const entry of entries) {
28
+ if (guard.checkStopped())
29
+ return;
30
+ if (shouldExcludeChild(real, entry.name, ignorePatterns))
31
+ continue;
32
+ const full = path.join(dir, entry.name);
33
+ if (entry.isDirectory()) {
34
+ yield* walk(full, rootReal, ignorePatterns, seen, guard, depth + 1, context);
35
+ }
36
+ else if (entry.isFile()) {
37
+ yield full;
38
+ }
39
+ else if (entry.isSymbolicLink()) {
40
+ try {
41
+ const targetReal = await fs.realpath(full);
42
+ if (!isSafeSymlinkTarget(targetReal, rootReal, context))
43
+ continue;
44
+ const stat = await fs.stat(targetReal);
45
+ if (stat.isDirectory()) {
46
+ yield* walk(targetReal, rootReal, ignorePatterns, seen, guard, depth + 1, context);
47
+ }
48
+ else if (stat.isFile()) {
49
+ yield full;
50
+ }
51
+ }
52
+ catch {
53
+ // Ignore broken or inaccessible symlinks.
54
+ }
55
+ }
100
56
  }
101
- }
102
- }
103
-
104
- /** True when the first block contains a NUL byte. */
105
- async function looksBinary(filePath) {
106
- let handle;
107
- try {
108
- handle = await fs.open(filePath, 'r');
109
- const buffer = Buffer.alloc(SNIFF_BYTES);
110
- const { bytesRead } = await handle.read(buffer, 0, SNIFF_BYTES, 0);
111
- return buffer.subarray(0, bytesRead).includes(0);
112
- } catch (e) {
113
- return true; // unreadable: treat as not searchable
114
- } finally {
115
- if (handle) await handle.close().catch(() => {});
116
- }
117
57
  }
118
-
119
58
  export const fsSearch = {
120
- schema: {
121
- name: 'fs.search',
122
- description: 'Search for text across files in a directory tree. Skips ignored and build directories, binary files, and files larger than 2 MB.',
123
- parameters: {
124
- type: 'object',
125
- properties: {
126
- query: { type: 'string', description: 'Text or regular expression to find.' },
127
- path: { type: 'string', description: 'Directory to search in. Defaults to the working directory.' },
128
- isRegex: { type: 'boolean', description: 'Treat the query as a regular expression.' },
129
- maxResults: { type: 'integer', description: `Stop after this many matching lines. Defaults to ${DEFAULT_MAX_RESULTS}.` }
130
- },
131
- required: ['query']
132
- }
133
- },
134
-
135
- async execute(args) {
136
- try {
137
- const searchPath = args.path || process.cwd();
138
- const maxResults = Number.isInteger(args.maxResults) && args.maxResults > 0
139
- ? Math.min(args.maxResults, 1000)
140
- : DEFAULT_MAX_RESULTS;
141
-
142
- let regex;
143
- try {
144
- regex = args.isRegex
145
- ? new RegExp(args.query)
146
- : new RegExp(args.query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
147
- } catch (e) {
148
- return { success: false, error: 'Invalid regular expression: ' + e.message };
149
- }
150
-
151
- const ignorePatterns = await loadIgnorePatterns(searchPath);
152
- const results = [];
153
- let filesScanned = 0;
154
- let filesSkipped = 0;
155
- let truncated = false;
156
-
157
- for await (const file of walk(searchPath, DEFAULT_EXCLUDES, ignorePatterns, new Set())) {
158
- if (results.length >= maxResults) { truncated = true; break; }
159
-
160
- let stat;
161
- try {
162
- stat = await fs.stat(file);
163
- } catch (e) { continue; }
164
- if (stat.size > MAX_FILE_BYTES) { filesSkipped++; continue; }
165
- if (await looksBinary(file)) { filesSkipped++; continue; }
166
-
167
- let content;
59
+ schema: {
60
+ name: 'fs.search',
61
+ description: 'Search for text across files in a directory tree. Enforces bounded depth/time, workspace & symlink safety, and skips build/system/binary files.',
62
+ parameters: {
63
+ type: 'object',
64
+ properties: {
65
+ query: { type: 'string', description: 'Text or regular expression to find.' },
66
+ path: { type: 'string', description: 'Directory or file to search in. Defaults to workspace root.' },
67
+ isRegex: { type: 'boolean', description: 'Treat the query as a regular expression.' },
68
+ maxResults: {
69
+ type: 'integer',
70
+ description: `Stop after this many matching lines. Defaults to ${DEFAULT_MAX_RESULTS}.`
71
+ }
72
+ },
73
+ required: ['query']
74
+ }
75
+ },
76
+ async execute(args, context) {
168
77
  try {
169
- content = await fs.readFile(file, 'utf8');
170
- } catch (e) { continue; }
171
- filesScanned++;
172
-
173
- const lines = content.split('\n');
174
- for (let i = 0; i < lines.length; i++) {
175
- if (!regex.test(lines[i])) continue;
176
- results.push(`${file}:${i + 1}:${lines[i].trim().slice(0, 300)}`);
177
- if (results.length >= maxResults) { truncated = true; break; }
78
+ if (!args || typeof args.query !== 'string' || args.query.length === 0) {
79
+ return { success: false, error: 'Missing required "query" argument.' };
80
+ }
81
+ const maxResults = typeof args.maxResults === 'number' && Number.isInteger(args.maxResults) && args.maxResults > 0
82
+ ? Math.min(args.maxResults, 1000)
83
+ : DEFAULT_MAX_RESULTS;
84
+ const compiled = compileSafeSearchRegex(args.query, {
85
+ isRegex: args.isRegex === true,
86
+ caseInsensitive: args.isRegex !== true
87
+ });
88
+ if (!compiled.regex) {
89
+ return { success: false, error: compiled.error || 'Invalid regular expression.' };
90
+ }
91
+ const regex = compiled.regex;
92
+ const searchPath = resolveSearchRoot(args.path, context);
93
+ const scope = checkSearchScope(searchPath, context);
94
+ if (!scope.allowed || !scope.realPath) {
95
+ return { success: false, error: scope.error || `Search path not allowed: ${searchPath}` };
96
+ }
97
+ const rootReal = scope.realPath;
98
+ let rootStat;
99
+ try {
100
+ rootStat = await fs.stat(rootReal);
101
+ }
102
+ catch {
103
+ return { success: false, error: `Search path does not exist: ${searchPath}` };
104
+ }
105
+ const maxDepth = typeof args.maxDepth === 'number' && Number.isInteger(args.maxDepth) && args.maxDepth > 0
106
+ ? Math.min(args.maxDepth, 24)
107
+ : undefined;
108
+ const guard = createTraversalGuard({ maxDepth, signal: context?.signal });
109
+ const results = [];
110
+ let filesScanned = 0;
111
+ let filesSkipped = 0;
112
+ let truncated = false;
113
+ const scanOneFile = async (file) => {
114
+ if (!guard.countFile())
115
+ return;
116
+ let stat;
117
+ try {
118
+ stat = await fs.stat(file);
119
+ }
120
+ catch {
121
+ return;
122
+ }
123
+ if (stat.size > MAX_FILE_BYTES) {
124
+ filesSkipped++;
125
+ return;
126
+ }
127
+ if (await looksBinaryFile(file)) {
128
+ filesSkipped++;
129
+ return;
130
+ }
131
+ let content;
132
+ try {
133
+ content = await fs.readFile(file, 'utf8');
134
+ }
135
+ catch {
136
+ return;
137
+ }
138
+ filesScanned++;
139
+ const lines = content.split('\n');
140
+ for (let i = 0; i < lines.length; i++) {
141
+ if (guard.checkStopped())
142
+ break;
143
+ const line = lines[i];
144
+ if (!regex.test(line))
145
+ continue;
146
+ results.push(`${file}:${i + 1}:${line.trim().slice(0, 300)}`);
147
+ if (results.length >= maxResults) {
148
+ truncated = true;
149
+ break;
150
+ }
151
+ }
152
+ };
153
+ if (rootStat.isFile()) {
154
+ await scanOneFile(searchPath);
155
+ }
156
+ else {
157
+ const ignorePatterns = await loadGitIgnoreNames(rootReal);
158
+ for await (const file of walk(rootReal, rootReal, ignorePatterns, new Set(), guard, 0, context)) {
159
+ if (results.length >= maxResults) {
160
+ truncated = true;
161
+ break;
162
+ }
163
+ if (guard.checkStopped())
164
+ break;
165
+ await scanOneFile(file);
166
+ if (results.length >= maxResults) {
167
+ truncated = true;
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ if (guard.stopReason === 'aborted') {
173
+ return { success: false, aborted: true, error: 'Search aborted.' };
174
+ }
175
+ const budgetNotice = guard.stopReason ? ` (${guard.stopNotice()})` : '';
176
+ if (results.length === 0) {
177
+ return {
178
+ success: true,
179
+ output: `No matches found. Scanned ${filesScanned} files under ${searchPath}` +
180
+ (filesSkipped > 0 ? `; skipped ${filesSkipped} binary or oversized files` : '') +
181
+ `${budgetNotice}.`
182
+ };
183
+ }
184
+ const footerParts = [];
185
+ if (truncated) {
186
+ footerParts.push(`stopped at ${maxResults} matches — narrow the query or raise maxResults`);
187
+ }
188
+ if (guard.stopReason) {
189
+ footerParts.push(guard.stopNotice());
190
+ }
191
+ const footer = footerParts.length > 0 ? `\n\n[${footerParts.join('; ')}]` : '';
192
+ return {
193
+ success: true,
194
+ output: results.join('\n') + footer
195
+ };
196
+ }
197
+ catch (error) {
198
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
178
199
  }
179
- }
180
-
181
- if (results.length === 0) {
182
- return {
183
- success: true,
184
- output: `No matches found. Scanned ${filesScanned} files under ${searchPath}` +
185
- (filesSkipped > 0 ? `; skipped ${filesSkipped} binary or oversized files.` : '.')
186
- };
187
- }
188
-
189
- return {
190
- success: true,
191
- output: results.join('\n') +
192
- (truncated ? `\n\n[stopped at ${maxResults} matches — narrow the query or raise maxResults]` : '')
193
- };
194
- } catch (e) {
195
- return { success: false, error: e.message };
196
200
  }
197
- }
198
201
  };
@@ -0,0 +1,241 @@
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
+ loadGitIgnoreNames,
10
+ looksBinaryFile,
11
+ resolveSearchRoot,
12
+ shouldExcludeChild,
13
+ type SearchExecutionContext,
14
+ type TraversalGuard
15
+ } from './walkerSafety.js';
16
+
17
+ const DEFAULT_MAX_RESULTS = 100;
18
+
19
+ export interface FsSearchArgs {
20
+ query: string;
21
+ path?: string | undefined;
22
+ isRegex?: boolean | undefined;
23
+ maxResults?: number | undefined;
24
+ maxDepth?: number | undefined;
25
+ }
26
+
27
+ export interface FsSearchResult {
28
+ success: boolean;
29
+ output?: string;
30
+ error?: string;
31
+ aborted?: boolean;
32
+ }
33
+
34
+ async function* walk(
35
+ dir: string,
36
+ rootReal: string,
37
+ ignorePatterns: readonly string[],
38
+ seen: Set<string>,
39
+ guard: TraversalGuard,
40
+ depth: number,
41
+ context?: SearchExecutionContext
42
+ ): AsyncGenerator<string> {
43
+ if (!guard.enterDir(depth)) return;
44
+
45
+ let real: string;
46
+ try {
47
+ real = await fs.realpath(dir);
48
+ } catch {
49
+ return;
50
+ }
51
+ if (!isSafeSymlinkTarget(real, rootReal, context)) return;
52
+ if (seen.has(real)) return;
53
+ seen.add(real);
54
+
55
+ let entries;
56
+ try {
57
+ entries = await fs.readdir(dir, { withFileTypes: true });
58
+ } catch {
59
+ return;
60
+ }
61
+
62
+ for (const entry of entries) {
63
+ if (guard.checkStopped()) return;
64
+ if (shouldExcludeChild(real, entry.name, ignorePatterns)) continue;
65
+ const full = path.join(dir, entry.name);
66
+
67
+ if (entry.isDirectory()) {
68
+ yield* walk(full, rootReal, ignorePatterns, seen, guard, depth + 1, context);
69
+ } else if (entry.isFile()) {
70
+ yield full;
71
+ } else if (entry.isSymbolicLink()) {
72
+ try {
73
+ const targetReal = await fs.realpath(full);
74
+ if (!isSafeSymlinkTarget(targetReal, rootReal, context)) continue;
75
+ const stat = await fs.stat(targetReal);
76
+ if (stat.isDirectory()) {
77
+ yield* walk(targetReal, rootReal, ignorePatterns, seen, guard, depth + 1, context);
78
+ } else if (stat.isFile()) {
79
+ yield full;
80
+ }
81
+ } catch {
82
+ // Ignore broken or inaccessible symlinks.
83
+ }
84
+ }
85
+ }
86
+ }
87
+
88
+ export const fsSearch = {
89
+ schema: {
90
+ name: 'fs.search',
91
+ description:
92
+ 'Search for text across files in a directory tree. Enforces bounded depth/time, workspace & symlink safety, and skips build/system/binary files.',
93
+ parameters: {
94
+ type: 'object',
95
+ properties: {
96
+ query: { type: 'string', description: 'Text or regular expression to find.' },
97
+ path: { type: 'string', description: 'Directory or file to search in. Defaults to workspace root.' },
98
+ isRegex: { type: 'boolean', description: 'Treat the query as a regular expression.' },
99
+ maxResults: {
100
+ type: 'integer',
101
+ description: `Stop after this many matching lines. Defaults to ${DEFAULT_MAX_RESULTS}.`
102
+ }
103
+ },
104
+ required: ['query']
105
+ }
106
+ },
107
+
108
+ async execute(
109
+ args: FsSearchArgs,
110
+ context?: SearchExecutionContext
111
+ ): Promise<FsSearchResult> {
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 maxResults =
118
+ typeof args.maxResults === 'number' && Number.isInteger(args.maxResults) && args.maxResults > 0
119
+ ? Math.min(args.maxResults, 1000)
120
+ : DEFAULT_MAX_RESULTS;
121
+
122
+ const compiled = compileSafeSearchRegex(args.query, {
123
+ isRegex: args.isRegex === true,
124
+ caseInsensitive: args.isRegex !== true
125
+ });
126
+ if (!compiled.regex) {
127
+ return { success: false, error: compiled.error || 'Invalid regular expression.' };
128
+ }
129
+ const regex = compiled.regex;
130
+
131
+ const searchPath = resolveSearchRoot(args.path, context);
132
+ const scope = checkSearchScope(searchPath, context);
133
+ if (!scope.allowed || !scope.realPath) {
134
+ return { success: false, error: scope.error || `Search path not allowed: ${searchPath}` };
135
+ }
136
+ const rootReal = scope.realPath;
137
+
138
+ let rootStat;
139
+ try {
140
+ rootStat = await fs.stat(rootReal);
141
+ } catch {
142
+ return { success: false, error: `Search path does not exist: ${searchPath}` };
143
+ }
144
+
145
+ const maxDepth =
146
+ typeof args.maxDepth === 'number' && Number.isInteger(args.maxDepth) && args.maxDepth > 0
147
+ ? Math.min(args.maxDepth, 24)
148
+ : undefined;
149
+ const guard = createTraversalGuard({ maxDepth, signal: context?.signal });
150
+ const results: string[] = [];
151
+ let filesScanned = 0;
152
+ let filesSkipped = 0;
153
+ let truncated = false;
154
+
155
+ const scanOneFile = async (file: string): Promise<void> => {
156
+ if (!guard.countFile()) return;
157
+ let stat;
158
+ try {
159
+ stat = await fs.stat(file);
160
+ } catch {
161
+ return;
162
+ }
163
+ if (stat.size > MAX_FILE_BYTES) {
164
+ filesSkipped++;
165
+ return;
166
+ }
167
+ if (await looksBinaryFile(file)) {
168
+ filesSkipped++;
169
+ return;
170
+ }
171
+ let content: string;
172
+ try {
173
+ content = await fs.readFile(file, 'utf8');
174
+ } catch {
175
+ return;
176
+ }
177
+ filesScanned++;
178
+ const lines = content.split('\n');
179
+ for (let i = 0; i < lines.length; i++) {
180
+ if (guard.checkStopped()) break;
181
+ const line = lines[i]!;
182
+ if (!regex.test(line)) continue;
183
+ results.push(`${file}:${i + 1}:${line.trim().slice(0, 300)}`);
184
+ if (results.length >= maxResults) {
185
+ truncated = true;
186
+ break;
187
+ }
188
+ }
189
+ };
190
+
191
+ if (rootStat.isFile()) {
192
+ await scanOneFile(searchPath);
193
+ } else {
194
+ const ignorePatterns = await loadGitIgnoreNames(rootReal);
195
+ for await (const file of walk(rootReal, rootReal, ignorePatterns, new Set(), guard, 0, context)) {
196
+ if (results.length >= maxResults) {
197
+ truncated = true;
198
+ break;
199
+ }
200
+ if (guard.checkStopped()) break;
201
+ await scanOneFile(file);
202
+ if (results.length >= maxResults) {
203
+ truncated = true;
204
+ break;
205
+ }
206
+ }
207
+ }
208
+
209
+ if (guard.stopReason === 'aborted') {
210
+ return { success: false, aborted: true, error: 'Search aborted.' };
211
+ }
212
+
213
+ const budgetNotice = guard.stopReason ? ` (${guard.stopNotice()})` : '';
214
+ if (results.length === 0) {
215
+ return {
216
+ success: true,
217
+ output:
218
+ `No matches found. Scanned ${filesScanned} files under ${searchPath}` +
219
+ (filesSkipped > 0 ? `; skipped ${filesSkipped} binary or oversized files` : '') +
220
+ `${budgetNotice}.`
221
+ };
222
+ }
223
+
224
+ const footerParts: string[] = [];
225
+ if (truncated) {
226
+ footerParts.push(`stopped at ${maxResults} matches — narrow the query or raise maxResults`);
227
+ }
228
+ if (guard.stopReason) {
229
+ footerParts.push(guard.stopNotice());
230
+ }
231
+ const footer = footerParts.length > 0 ? `\n\n[${footerParts.join('; ')}]` : '';
232
+
233
+ return {
234
+ success: true,
235
+ output: results.join('\n') + footer
236
+ };
237
+ } catch (error: unknown) {
238
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
239
+ }
240
+ }
241
+ };