@mrclrchtr/supi-lsp 1.3.1 → 1.4.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 (61) hide show
  1. package/README.md +58 -39
  2. package/node_modules/@mrclrchtr/supi-core/README.md +52 -41
  3. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  4. package/node_modules/@mrclrchtr/supi-core/src/api.ts +13 -13
  5. package/node_modules/@mrclrchtr/supi-core/src/{config-settings.ts → config/config-settings.ts} +2 -2
  6. package/node_modules/@mrclrchtr/supi-core/src/{context-provider-registry.ts → context/context-provider-registry.ts} +1 -1
  7. package/node_modules/@mrclrchtr/supi-core/src/extension.ts +1 -1
  8. package/node_modules/@mrclrchtr/supi-core/src/index.ts +13 -13
  9. package/node_modules/@mrclrchtr/supi-core/src/{settings-registry.ts → settings/settings-registry.ts} +1 -1
  10. package/package.json +3 -2
  11. package/src/api.ts +16 -3
  12. package/src/client/client-refresh.ts +1 -1
  13. package/src/client/client.ts +27 -3
  14. package/src/client/transport.ts +61 -5
  15. package/src/config/tsconfig-scope.ts +244 -0
  16. package/src/{types.ts → config/types.ts} +4 -2
  17. package/src/coordinates.ts +11 -0
  18. package/src/diagnostics/diagnostic-augmentation.ts +5 -5
  19. package/src/diagnostics/diagnostic-context.ts +115 -0
  20. package/src/diagnostics/diagnostic-display.ts +1 -1
  21. package/src/diagnostics/diagnostic-summary.ts +3 -2
  22. package/src/diagnostics/diagnostics.ts +1 -1
  23. package/src/diagnostics/stale-diagnostics.ts +1 -1
  24. package/src/diagnostics/suppression-diagnostics.ts +1 -1
  25. package/src/{workspace-sentinels.ts → diagnostics/workspace-sentinels.ts} +2 -2
  26. package/src/format.ts +2 -23
  27. package/src/index.ts +18 -5
  28. package/src/lsp.ts +72 -120
  29. package/src/manager/manager-diagnostics.ts +1 -1
  30. package/src/manager/manager-helpers.ts +4 -2
  31. package/src/manager/manager-project-info.ts +10 -7
  32. package/src/manager/manager-workspace-recovery.ts +1 -1
  33. package/src/manager/manager-workspace-symbol.ts +158 -6
  34. package/src/manager/manager.ts +202 -43
  35. package/src/{lsp-state.ts → session/lsp-state.ts} +22 -11
  36. package/src/{scanner.ts → session/scanner.ts} +3 -3
  37. package/src/{service-registry.ts → session/service-registry.ts} +104 -12
  38. package/src/{settings-registration.ts → session/settings-registration.ts} +1 -1
  39. package/src/session/tree-persist.ts +75 -0
  40. package/src/summary.ts +1 -1
  41. package/src/tool/guidance.ts +138 -0
  42. package/src/tool/names.ts +19 -0
  43. package/src/{overrides.ts → tool/overrides.ts} +55 -24
  44. package/src/tool/register-tools.ts +224 -0
  45. package/src/tool/service-actions.ts +258 -0
  46. package/src/{ui.ts → ui/ui.ts} +4 -4
  47. package/src/utils.ts +11 -0
  48. package/src/guidance.ts +0 -163
  49. package/src/search-fallback.ts +0 -98
  50. package/src/tool-actions.ts +0 -430
  51. package/src/tree-persist.ts +0 -48
  52. package/src/tsconfig-scope.ts +0 -156
  53. /package/node_modules/@mrclrchtr/supi-core/src/{config.ts → config/config.ts} +0 -0
  54. /package/node_modules/@mrclrchtr/supi-core/src/{context-messages.ts → context/context-messages.ts} +0 -0
  55. /package/node_modules/@mrclrchtr/supi-core/src/{context-tag.ts → context/context-tag.ts} +0 -0
  56. /package/node_modules/@mrclrchtr/supi-core/src/{settings-command.ts → settings/settings-command.ts} +0 -0
  57. /package/node_modules/@mrclrchtr/supi-core/src/{settings-ui.ts → settings/settings-ui.ts} +0 -0
  58. /package/src/{capabilities.ts → config/capabilities.ts} +0 -0
  59. /package/src/{config.ts → config/config.ts} +0 -0
  60. /package/src/{defaults.json → config/defaults.json} +0 -0
  61. /package/src/{renderer.ts → ui/renderer.ts} +0 -0
@@ -0,0 +1,258 @@
1
+ // Service-backed LSP tool actions used by the public expert toolset.
2
+
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import type { Position } from "../config/types.ts";
6
+ import { formatDiagnostics } from "../diagnostics/diagnostics.ts";
7
+ import {
8
+ formatCodeActions,
9
+ formatDocumentSymbols,
10
+ formatHover,
11
+ formatLocations,
12
+ formatSymbolInformation,
13
+ formatWorkspaceEdit,
14
+ formatWorkspaceSymbols,
15
+ normalizeLocations,
16
+ } from "../format.ts";
17
+ import type { SessionLspService } from "../session/service-registry.ts";
18
+ import { resolveSessionPath } from "../utils.ts";
19
+
20
+ export type LspLookupKind = "hover" | "definition" | "references" | "implementation";
21
+ export type LspRefactorKind = "rename" | "code_actions";
22
+
23
+ export interface LspLookupToolParams {
24
+ kind: LspLookupKind;
25
+ file: string;
26
+ line: number;
27
+ character: number;
28
+ }
29
+
30
+ export interface LspDocumentSymbolsToolParams {
31
+ file: string;
32
+ }
33
+
34
+ export interface LspWorkspaceSymbolsToolParams {
35
+ query: string;
36
+ }
37
+
38
+ export interface LspDiagnosticsToolParams {
39
+ file?: string;
40
+ }
41
+
42
+ export interface LspRefactorToolParams {
43
+ kind: LspRefactorKind;
44
+ file: string;
45
+ line: number;
46
+ character: number;
47
+ newName?: string;
48
+ }
49
+
50
+ function validatePositivePosition(line: number, character: number): string | null {
51
+ if (!Number.isInteger(line) || line < 1) {
52
+ return "Validation error: `line` must be a positive 1-based integer.";
53
+ }
54
+ if (!Number.isInteger(character) || character < 1) {
55
+ return "Validation error: `character` must be a positive 1-based integer.";
56
+ }
57
+ return null;
58
+ }
59
+
60
+ function toZeroBased(line: number, character: number): Position {
61
+ return { line: line - 1, character: character - 1 };
62
+ }
63
+
64
+ function validateFile(service: SessionLspService, cwd: string, file: string): string | null {
65
+ const resolvedPath = resolveSessionPath(cwd, file);
66
+ if (!fs.existsSync(resolvedPath)) {
67
+ return `File not found: \`${file}\``;
68
+ }
69
+ if (!service.isSupportedSourceFile(file)) {
70
+ return noServerMessage(resolvedPath);
71
+ }
72
+ return null;
73
+ }
74
+
75
+ function noServerMessage(filePath: string): string {
76
+ return `No LSP server available for this file type (${path.extname(filePath) || "unknown"})`;
77
+ }
78
+
79
+ function formatUnexpectedFailure(label: string, error: unknown): string {
80
+ const message = error instanceof Error ? error.message : String(error);
81
+ return `LSP ${label} failed: ${message}`;
82
+ }
83
+
84
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: semantic lookup dispatch stays clearer as a single position-based switch.
85
+ export async function executeLookup(
86
+ service: SessionLspService,
87
+ cwd: string,
88
+ params: LspLookupToolParams,
89
+ ): Promise<string> {
90
+ try {
91
+ const positionError = validatePositivePosition(params.line, params.character);
92
+ if (positionError) return positionError;
93
+
94
+ const fileError = validateFile(service, cwd, params.file);
95
+ if (fileError) return fileError;
96
+
97
+ const position = toZeroBased(params.line, params.character);
98
+ switch (params.kind) {
99
+ case "hover": {
100
+ const hover = await service.hover(params.file, position);
101
+ return hover ? formatHover(hover) : "No hover information available at this position.";
102
+ }
103
+ case "definition": {
104
+ const result = await service.definition(params.file, position);
105
+ if (!result) return "No definition found.";
106
+ const locations = normalizeLocations(result);
107
+ return locations.length > 0
108
+ ? formatLocations("Definition", locations, cwd)
109
+ : "No definition found.";
110
+ }
111
+ case "references": {
112
+ const references = await service.references(params.file, position);
113
+ return references && references.length > 0
114
+ ? formatLocations("References", references, cwd)
115
+ : "No references found.";
116
+ }
117
+ case "implementation": {
118
+ const result = await service.implementation(params.file, position);
119
+ if (!result) return "No implementation found.";
120
+ const locations = normalizeLocations(result);
121
+ return locations.length > 0
122
+ ? formatLocations("Implementation", locations, cwd)
123
+ : "No implementation found.";
124
+ }
125
+ }
126
+ } catch (error) {
127
+ return formatUnexpectedFailure("lookup", error);
128
+ }
129
+ }
130
+
131
+ export async function executeDocumentSymbols(
132
+ service: SessionLspService,
133
+ cwd: string,
134
+ params: LspDocumentSymbolsToolParams,
135
+ ): Promise<string> {
136
+ try {
137
+ const fileError = validateFile(service, cwd, params.file);
138
+ if (fileError) return fileError;
139
+
140
+ const symbols = await service.documentSymbols(params.file);
141
+ if (!symbols || symbols.length === 0) return "No document symbols found.";
142
+
143
+ if ("children" in symbols[0] || "selectionRange" in symbols[0]) {
144
+ return formatDocumentSymbols(symbols as import("../config/types.ts").DocumentSymbol[], 0);
145
+ }
146
+ return formatSymbolInformation(
147
+ symbols as import("../config/types.ts").SymbolInformation[],
148
+ cwd,
149
+ );
150
+ } catch (error) {
151
+ return formatUnexpectedFailure("document symbol lookup", error);
152
+ }
153
+ }
154
+
155
+ export async function executeWorkspaceSymbols(
156
+ service: SessionLspService,
157
+ cwd: string,
158
+ params: LspWorkspaceSymbolsToolParams,
159
+ ): Promise<string> {
160
+ try {
161
+ const query = params.query.trim();
162
+ if (query.length === 0) {
163
+ return "Validation error: `query` must be a non-empty string.";
164
+ }
165
+
166
+ const symbols = await service.workspaceSymbol(query);
167
+ if (!symbols) return "Workspace symbol search is not supported by the active language servers.";
168
+ if (symbols.length === 0) return `No symbols found for query \`${query}\`.`;
169
+
170
+ return formatWorkspaceSymbols(symbols, cwd);
171
+ } catch (error) {
172
+ return formatUnexpectedFailure("workspace symbol lookup", error);
173
+ }
174
+ }
175
+
176
+ export async function executeDiagnostics(
177
+ service: SessionLspService,
178
+ cwd: string,
179
+ params: LspDiagnosticsToolParams,
180
+ ): Promise<string> {
181
+ try {
182
+ if (params.file) {
183
+ const resolvedPath = resolveSessionPath(cwd, params.file);
184
+ if (!fs.existsSync(resolvedPath)) {
185
+ return `File not found: \`${params.file}\``;
186
+ }
187
+ if (!service.isSupportedSourceFile(params.file)) {
188
+ return noServerMessage(resolvedPath);
189
+ }
190
+
191
+ const diagnostics = await service.fileDiagnostics(params.file, 4);
192
+ if (!diagnostics) return noServerMessage(resolvedPath);
193
+ return formatDiagnostics(resolvedPath, diagnostics, cwd);
194
+ }
195
+
196
+ const summary = service.getWorkspaceDiagnosticSummary();
197
+ if (summary.length === 0) return "No diagnostics across any files.";
198
+
199
+ const lines = ["## Diagnostics Summary", ""];
200
+ for (const entry of summary) {
201
+ lines.push(`- **${entry.file}**: ${entry.errors} error(s), ${entry.warnings} warning(s)`);
202
+ }
203
+ return lines.join("\n");
204
+ } catch (error) {
205
+ return formatUnexpectedFailure("diagnostics", error);
206
+ }
207
+ }
208
+
209
+ export async function executeRefactor(
210
+ service: SessionLspService,
211
+ cwd: string,
212
+ params: LspRefactorToolParams,
213
+ ): Promise<string> {
214
+ try {
215
+ const positionError = validatePositivePosition(params.line, params.character);
216
+ if (positionError) return positionError;
217
+
218
+ const fileError = validateFile(service, cwd, params.file);
219
+ if (fileError) return fileError;
220
+
221
+ const position = toZeroBased(params.line, params.character);
222
+
223
+ if (params.kind === "rename") {
224
+ if (!params.newName || params.newName.trim().length === 0) {
225
+ return "Validation error: `newName` is required for rename.";
226
+ }
227
+
228
+ const edit = await service.rename(params.file, position, params.newName.trim());
229
+ return edit ? formatWorkspaceEdit(edit, cwd) : "Rename not available at this position.";
230
+ }
231
+
232
+ const actions = await service.codeActions(params.file, position);
233
+ return actions && actions.length > 0
234
+ ? formatCodeActions(actions)
235
+ : "No code actions available at this position.";
236
+ } catch (error) {
237
+ return formatUnexpectedFailure("refactor", error);
238
+ }
239
+ }
240
+
241
+ export async function executeRecover(service: SessionLspService): Promise<string> {
242
+ try {
243
+ const result = await service.recoverDiagnostics({ restartIfStillStale: true });
244
+ const refreshed = pluralize(result.refreshedClients, "client");
245
+ const restarted = pluralize(result.restartedClients, "client");
246
+ const status = result.staleAssessment.suspected
247
+ ? "stale diagnostics still suspected"
248
+ : "stale diagnostics cleared";
249
+ const warning = result.staleAssessment.warning ? ` — ${result.staleAssessment.warning}` : "";
250
+ return `LSP recovery complete: refreshed ${refreshed}, restarted ${restarted}, ${status}${warning}.`;
251
+ } catch (error) {
252
+ return formatUnexpectedFailure("recovery", error);
253
+ }
254
+ }
255
+
256
+ function pluralize(count: number, word: string): string {
257
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
258
+ }
@@ -2,10 +2,10 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { DynamicBorder } from "@earendil-works/pi-coding-agent";
3
3
  import type { OverlayHandle } from "@earendil-works/pi-tui";
4
4
  import { Container, Spacer, Text } from "@earendil-works/pi-tui";
5
- import type { LspManager } from "./manager/manager.ts";
6
- import type { OutstandingDiagnosticSummaryEntry } from "./manager/manager-types.ts";
7
- import type { Diagnostic, ProjectServerInfo } from "./types.ts";
8
- import { DiagnosticSeverity } from "./types.ts";
5
+ import type { Diagnostic, ProjectServerInfo } from "../config/types.ts";
6
+ import { DiagnosticSeverity } from "../config/types.ts";
7
+ import type { LspManager } from "../manager/manager.ts";
8
+ import type { OutstandingDiagnosticSummaryEntry } from "../manager/manager-types.ts";
9
9
 
10
10
  export interface LspInspectorState {
11
11
  handle: OverlayHandle | null;
package/src/utils.ts CHANGED
@@ -27,6 +27,17 @@ export function uriToFile(uri: string): string {
27
27
  return filePath;
28
28
  }
29
29
 
30
+ /**
31
+ * Resolve a tool-style file path against the active session cwd.
32
+ *
33
+ * Built-in pi file tools accept a leading `@` prefix in path arguments, so LSP
34
+ * helpers strip that prefix as well before resolving relative paths.
35
+ */
36
+ export function resolveSessionPath(cwd: string, filePath: string): string {
37
+ const normalizedPath = filePath.startsWith("@") ? filePath.slice(1) : filePath;
38
+ return path.resolve(cwd, normalizedPath);
39
+ }
40
+
30
41
  // ── Language ID Detection ─────────────────────────────────────────────
31
42
 
32
43
  const EXT_TO_LANGUAGE: Record<string, string> = {
package/src/guidance.ts DELETED
@@ -1,163 +0,0 @@
1
- import * as path from "node:path";
2
- import { splitSuppressionDiagnostics } from "./diagnostics/suppression-diagnostics.ts";
3
- import type { OutstandingDiagnosticSummaryEntry } from "./manager/manager-types.ts";
4
- import type { Diagnostic, ProjectServerInfo } from "./types.ts";
5
-
6
- export const lspPromptSnippet =
7
- "Use semantic code intelligence for hover, definitions, references, symbols, rename planning, code actions, and diagnostics in supported languages.";
8
-
9
- export const lspPromptGuidelines = [
10
- "Prefer the lsp tool over bash text search for supported source files when the task is semantic code navigation or diagnostics.",
11
- "Use lsp for hover, definitions, references, document symbols, rename planning, code actions, and diagnostics before falling back to grep-style shell search.",
12
- "Fall back to bash/read when LSP is unavailable, the file type is unsupported, or the task is plain-text search across docs, config files, or string literals.",
13
- "Diagnostics are automatically delivered: inline after every write/edit tool result, and as context before each agent turn. You do not need to call the lsp tool to check them — they are already in your context.",
14
- "When delivered diagnostics show errors, decide: (a) expected temporary state from a planned multi-step change — continue your sequence, then verify at the end; (b) unexpected 'Cannot find module', unresolved imports, or type mismatches — stop and fix the root cause before editing more files.",
15
- "When the SAME error pattern appears across MULTIPLE files after you changed imports, dependencies, or shared types, it is a systemic root-cause issue (missing install, broken import path, wrong dependency version). Do not patch each file individually — find and fix the root cause first.",
16
- "When diagnostics look stale after package.json, lockfile, tsconfig, or generated-type changes, use lsp recover before editing more files.",
17
- "After changing package.json dependencies, imports, or peer dependencies, run the package manager install command (e.g., pnpm install) before concluding that module resolution errors are real code bugs.",
18
- ];
19
-
20
- /**
21
- * Build per-project `promptGuidelines` for the `lsp` tool registration.
22
- * These guidelines are part of pi's stable system prompt after session-start
23
- * tool registration, avoiding per-turn `before_agent_start` prompt overrides.
24
- */
25
- export function buildProjectGuidelines(servers: ProjectServerInfo[], cwd: string): string[] {
26
- const dynamic = servers.map((server) => {
27
- const root = displayRoot(server.root, cwd);
28
- const fileTypes = server.fileTypes.map((entry) => `.${entry}`).join(", ");
29
- const actions = server.supportedActions.join(", ");
30
- const status = server.status === "running" ? "active" : "unavailable";
31
- const actionText = actions.length > 0 ? ` | actions: ${actions}` : "";
32
- return `LSP ${status}: ${server.name} | root: ${root} | files: ${fileTypes}${actionText}`;
33
- });
34
-
35
- return [
36
- ...lspPromptGuidelines.slice(0, 2),
37
- "Use lsp before grep/rg/find for understanding code, finding usages, diagnostics, symbol lookup, and refactors in supported languages.",
38
- ...dynamic,
39
- "Use lsp actions by task: hover/definition/references/symbols for understanding code, references/workspace_symbol/search for usages, diagnostics/hover/code_actions for issues, and rename/code_actions for refactors.",
40
- ...lspPromptGuidelines.slice(2),
41
- ].filter(Boolean);
42
- }
43
-
44
- export const MAX_DETAILED_DIAGNOSTICS = 5;
45
- const MAX_DETAIL_LINES_PER_FILE = 3;
46
-
47
- interface DetailedDiagnostics {
48
- file: string;
49
- diagnostics: Diagnostic[];
50
- }
51
-
52
- export function formatDiagnosticsContext(
53
- diagnostics: OutstandingDiagnosticSummaryEntry[],
54
- maxFiles: number = 3,
55
- detailed?: DetailedDiagnostics[],
56
- staleWarning?: string | null,
57
- ): string | null {
58
- if (diagnostics.length === 0) return null;
59
-
60
- const totalDiags = diagnostics.reduce((sum, d) => sum + d.total, 0);
61
- const detailMap = buildDetailMap(diagnostics, totalDiags, detailed);
62
-
63
- const lines: string[] = [];
64
- if (staleWarning) lines.push(staleWarning);
65
- const visible = diagnostics.slice(0, maxFiles);
66
-
67
- for (const entry of visible) {
68
- lines.push(`- ${entry.file}: ${formatCounts(entry)}`);
69
- appendDetailLines(lines, detailMap?.get(entry.file));
70
- }
71
-
72
- const remaining = diagnostics.length - visible.length;
73
- if (remaining > 0) {
74
- lines.push(`- +${remaining} more file${remaining === 1 ? "" : "s"}`);
75
- }
76
-
77
- appendSuppressionCleanup(
78
- lines,
79
- visible.map((entry) => entry.file),
80
- detailMap,
81
- );
82
-
83
- return [
84
- '<extension-context source="supi-lsp">',
85
- "Outstanding diagnostics — fix these before proceeding:",
86
- ...lines,
87
- "</extension-context>",
88
- ].join("\n");
89
- }
90
-
91
- function buildDetailMap(
92
- _diagnostics: OutstandingDiagnosticSummaryEntry[],
93
- totalDiags: number,
94
- detailed?: DetailedDiagnostics[],
95
- ): Map<string, Diagnostic[]> | null {
96
- if (totalDiags > MAX_DETAILED_DIAGNOSTICS || !detailed || detailed.length === 0) return null;
97
- return new Map(detailed.map((d) => [d.file, d.diagnostics]));
98
- }
99
-
100
- function appendDetailLines(lines: string[], details?: Diagnostic[]): void {
101
- if (!details) return;
102
- for (const d of details.slice(0, MAX_DETAIL_LINES_PER_FILE)) {
103
- const line = d.range.start.line + 1;
104
- const char = d.range.start.character + 1;
105
- const source = d.source ? ` ${d.source}` : "";
106
- lines.push(` L${line} C${char}${source}: ${d.message}`);
107
- }
108
- if (details.length > MAX_DETAIL_LINES_PER_FILE) {
109
- const extra = details.length - MAX_DETAIL_LINES_PER_FILE;
110
- lines.push(` +${extra} more`);
111
- }
112
- }
113
-
114
- function appendSuppressionCleanup(
115
- lines: string[],
116
- visibleFiles: string[],
117
- detailMap: Map<string, Diagnostic[]> | null,
118
- ): void {
119
- if (!detailMap) return;
120
-
121
- const suppressionLines: string[] = [];
122
- for (const file of visibleFiles) {
123
- const diagnostics = detailMap.get(file);
124
- if (!diagnostics) continue;
125
-
126
- const { suppressions } = splitSuppressionDiagnostics(diagnostics, 1);
127
- if (suppressions.length === 0) continue;
128
-
129
- suppressionLines.push(`- ${file}`);
130
- appendDetailLines(suppressionLines, suppressions);
131
- }
132
-
133
- if (suppressionLines.length === 0) return;
134
- lines.push("", "Stale suppression comments — clean these up:", ...suppressionLines);
135
- }
136
-
137
- export function diagnosticsContextFingerprint(content: string | null): string | null {
138
- return content;
139
- }
140
-
141
- // reorderDiagnosticContextMessages, getContextToken, and findLastUserMessageIndex
142
- // have been extracted to supi-core/context-messages.ts.
143
- // Use pruneAndReorderContextMessages(messages, "lsp-context", activeToken) instead.
144
-
145
- function formatCounts(entry: OutstandingDiagnosticSummaryEntry): string {
146
- const counts: string[] = [];
147
- if (entry.errors > 0) counts.push(pluralize(entry.errors, "error"));
148
- if (entry.warnings > 0) counts.push(pluralize(entry.warnings, "warning"));
149
- if (entry.information > 0) counts.push(pluralize(entry.information, "info"));
150
- if (entry.hints > 0) counts.push(pluralize(entry.hints, "hint"));
151
- return counts.join(", ");
152
- }
153
-
154
- function displayRoot(root: string, cwd: string): string {
155
- const relative = path.relative(cwd, root);
156
- if (relative === "") return ".";
157
- if (relative.startsWith(`..${path.sep}`) || relative === "..") return root;
158
- return relative.replaceAll(path.sep, "/");
159
- }
160
-
161
- function pluralize(count: number, word: string): string {
162
- return `${count} ${word}${count === 1 ? "" : "s"}`;
163
- }
@@ -1,98 +0,0 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
-
4
- export interface GrepMatch {
5
- file: string;
6
- line: number;
7
- text: string;
8
- }
9
-
10
- const IGNORE_DIRS = new Set([
11
- "node_modules",
12
- ".git",
13
- "dist",
14
- "build",
15
- ".next",
16
- "coverage",
17
- "tmp",
18
- ".pnpm",
19
- ]);
20
-
21
- const SOURCE_EXTENSIONS = new Set([
22
- ".ts",
23
- ".tsx",
24
- ".js",
25
- ".jsx",
26
- ".mjs",
27
- ".cjs",
28
- ".py",
29
- ".rs",
30
- ".go",
31
- ".java",
32
- ".kt",
33
- ".swift",
34
- ".rb",
35
- ".c",
36
- ".cpp",
37
- ".h",
38
- ".hpp",
39
- ]);
40
-
41
- /** Simple recursive text search in project source files. */
42
- export function fallbackGrep(projectRoot: string, query: string): GrepMatch[] {
43
- const results: GrepMatch[] = [];
44
- walk(projectRoot, projectRoot, query, results);
45
- return results;
46
- }
47
-
48
- function walk(dir: string, projectRoot: string, query: string, results: GrepMatch[]): void {
49
- let entries: fs.Dirent[];
50
- try {
51
- entries = fs.readdirSync(dir, { withFileTypes: true });
52
- } catch {
53
- return;
54
- }
55
-
56
- for (const entry of entries) {
57
- if (entry.isDirectory()) {
58
- if (!IGNORE_DIRS.has(entry.name)) {
59
- walk(path.join(dir, entry.name), projectRoot, query, results);
60
- }
61
- continue;
62
- }
63
-
64
- if (!entry.isFile() || !SOURCE_EXTENSIONS.has(path.extname(entry.name))) {
65
- continue;
66
- }
67
-
68
- const filePath = path.join(dir, entry.name);
69
- searchFile(filePath, projectRoot, query, results);
70
- if (results.length >= 20) return;
71
- }
72
- }
73
-
74
- function searchFile(
75
- filePath: string,
76
- projectRoot: string,
77
- query: string,
78
- results: GrepMatch[],
79
- ): void {
80
- let content: string;
81
- try {
82
- content = fs.readFileSync(filePath, "utf-8");
83
- } catch {
84
- return;
85
- }
86
-
87
- const lines = content.split("\n");
88
- for (let i = 0; i < lines.length; i++) {
89
- if (lines[i].includes(query)) {
90
- results.push({
91
- file: path.relative(projectRoot, filePath),
92
- line: i + 1,
93
- text: lines[i].trim(),
94
- });
95
- if (results.length >= 20) return;
96
- }
97
- }
98
- }