@hasna/terminal 2.3.1 → 2.3.2

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 (66) hide show
  1. package/dist/App.js +404 -0
  2. package/dist/Browse.js +79 -0
  3. package/dist/FuzzyPicker.js +47 -0
  4. package/dist/Onboarding.js +51 -0
  5. package/dist/Spinner.js +12 -0
  6. package/dist/StatusBar.js +49 -0
  7. package/dist/ai.js +322 -0
  8. package/dist/cache.js +41 -0
  9. package/dist/command-rewriter.js +64 -0
  10. package/dist/command-validator.js +86 -0
  11. package/dist/compression.js +107 -0
  12. package/dist/context-hints.js +275 -0
  13. package/dist/diff-cache.js +107 -0
  14. package/dist/discover.js +212 -0
  15. package/dist/economy.js +123 -0
  16. package/dist/expand-store.js +38 -0
  17. package/dist/file-cache.js +72 -0
  18. package/dist/file-index.js +62 -0
  19. package/dist/history.js +62 -0
  20. package/dist/lazy-executor.js +54 -0
  21. package/dist/line-dedup.js +59 -0
  22. package/dist/loop-detector.js +75 -0
  23. package/dist/mcp/install.js +98 -0
  24. package/dist/mcp/server.js +569 -0
  25. package/dist/noise-filter.js +86 -0
  26. package/dist/output-processor.js +129 -0
  27. package/dist/output-router.js +41 -0
  28. package/dist/output-store.js +111 -0
  29. package/dist/parsers/base.js +2 -0
  30. package/dist/parsers/build.js +64 -0
  31. package/dist/parsers/errors.js +101 -0
  32. package/dist/parsers/files.js +78 -0
  33. package/dist/parsers/git.js +99 -0
  34. package/dist/parsers/index.js +48 -0
  35. package/dist/parsers/tests.js +89 -0
  36. package/dist/providers/anthropic.js +39 -0
  37. package/dist/providers/base.js +4 -0
  38. package/dist/providers/cerebras.js +95 -0
  39. package/dist/providers/groq.js +95 -0
  40. package/dist/providers/index.js +73 -0
  41. package/dist/providers/xai.js +95 -0
  42. package/dist/recipes/model.js +20 -0
  43. package/dist/recipes/storage.js +136 -0
  44. package/dist/search/content-search.js +68 -0
  45. package/dist/search/file-search.js +61 -0
  46. package/dist/search/filters.js +34 -0
  47. package/dist/search/index.js +5 -0
  48. package/dist/search/semantic.js +320 -0
  49. package/dist/session-boot.js +59 -0
  50. package/dist/session-context.js +55 -0
  51. package/dist/sessions-db.js +173 -0
  52. package/dist/smart-display.js +286 -0
  53. package/dist/snapshots.js +51 -0
  54. package/dist/supervisor.js +112 -0
  55. package/dist/test-watchlist.js +131 -0
  56. package/dist/tool-profiles.js +122 -0
  57. package/dist/tree.js +94 -0
  58. package/dist/usage-cache.js +65 -0
  59. package/package.json +8 -1
  60. package/.claude/scheduled_tasks.lock +0 -1
  61. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -20
  62. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -14
  63. package/CONTRIBUTING.md +0 -80
  64. package/benchmarks/benchmark.mjs +0 -115
  65. package/imported_modules.txt +0 -0
  66. package/tsconfig.json +0 -15
@@ -0,0 +1,68 @@
1
+ // Smart content search — structured grep/ripgrep with grouping and dedup
2
+ import { spawn } from "child_process";
3
+ import { DEFAULT_EXCLUDE_DIRS, relevanceScore } from "./filters.js";
4
+ function exec(command, cwd) {
5
+ return new Promise((resolve) => {
6
+ const proc = spawn("/bin/zsh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
7
+ let out = "";
8
+ proc.stdout?.on("data", (d) => { out += d.toString(); });
9
+ proc.on("close", () => resolve(out));
10
+ });
11
+ }
12
+ export async function searchContent(pattern, cwd, options = {}) {
13
+ const { fileType, maxResults = 30, contextLines = 0 } = options;
14
+ // Prefer ripgrep, fall back to grep
15
+ const excludeArgs = DEFAULT_EXCLUDE_DIRS.map(d => `--glob '!${d}'`).join(" ");
16
+ const typeArg = fileType ? `--type ${fileType}` : "";
17
+ const contextArg = contextLines > 0 ? `-C ${contextLines}` : "";
18
+ // Try rg first, fall back to grep
19
+ const rgCmd = `rg --line-number --no-heading ${contextArg} ${typeArg} ${excludeArgs} '${pattern.replace(/'/g, "'\\''")}' 2>/dev/null | head -500`;
20
+ const grepCmd = `grep -rn ${contextArg} '${pattern.replace(/'/g, "'\\''")}' . --include='*.ts' --include='*.js' --include='*.py' --include='*.go' --include='*.rs' --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist 2>/dev/null | head -500`;
21
+ let raw = await exec(rgCmd, cwd);
22
+ if (!raw.trim()) {
23
+ raw = await exec(grepCmd, cwd);
24
+ }
25
+ const lines = raw.split("\n").filter(l => l.trim());
26
+ const fileMap = new Map();
27
+ let filteredCount = 0;
28
+ for (const line of lines) {
29
+ // Format: path:line:content
30
+ const match = line.match(/^([^:]+):(\d+):(.*)$/);
31
+ if (!match)
32
+ continue;
33
+ const [, path, lineNum, content] = match;
34
+ if (DEFAULT_EXCLUDE_DIRS.some(d => path.includes(`/${d}/`))) {
35
+ filteredCount++;
36
+ continue;
37
+ }
38
+ if (!fileMap.has(path))
39
+ fileMap.set(path, []);
40
+ fileMap.get(path).push({
41
+ line: parseInt(lineNum),
42
+ content: content.trim(),
43
+ });
44
+ }
45
+ // Sort files by relevance
46
+ const files = [...fileMap.entries()]
47
+ .map(([path, matches]) => ({
48
+ path,
49
+ matches: matches.slice(0, 5), // max 5 matches per file
50
+ relevance: relevanceScore(path),
51
+ }))
52
+ .sort((a, b) => b.relevance - a.relevance)
53
+ .slice(0, maxResults);
54
+ const totalMatches = [...fileMap.values()].reduce((sum, m) => sum + m.length, 0);
55
+ const filtered = filteredCount > 0 ? [{ count: filteredCount, reason: "excluded directories" }] : [];
56
+ const rawTokens = Math.ceil(raw.length / 4);
57
+ const result = { query: pattern, totalMatches, files, filtered };
58
+ const resultTokens = Math.ceil(JSON.stringify(result).length / 4);
59
+ result.tokensSaved = Math.max(0, rawTokens - resultTokens);
60
+ // Overflow guard — warn when results are truncated
61
+ if (totalMatches > maxResults * 3) {
62
+ result.overflow = {
63
+ warning: `${totalMatches} total matches across ${fileMap.size} files — showing top ${files.length}`,
64
+ suggestion: "Try a more specific pattern, add fileType filter, or use -l to list files only",
65
+ };
66
+ }
67
+ return result;
68
+ }
@@ -0,0 +1,61 @@
1
+ // Smart file search — structured, filtered, token-efficient results
2
+ import { spawn } from "child_process";
3
+ import { DEFAULT_EXCLUDE_DIRS, isSourceFile, isExcludedDir, relevanceScore } from "./filters.js";
4
+ function exec(command, cwd) {
5
+ return new Promise((resolve) => {
6
+ const proc = spawn("/bin/zsh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
7
+ let out = "";
8
+ proc.stdout?.on("data", (d) => { out += d.toString(); });
9
+ proc.stderr?.on("data", (d) => { out += d.toString(); });
10
+ proc.on("close", () => resolve(out));
11
+ });
12
+ }
13
+ export async function searchFiles(pattern, cwd, options = {}) {
14
+ const { includeNodeModules = false, maxResults = 50 } = options;
15
+ // Build find command
16
+ const excludes = includeNodeModules
17
+ ? DEFAULT_EXCLUDE_DIRS.filter(d => d !== "node_modules")
18
+ : DEFAULT_EXCLUDE_DIRS;
19
+ const excludeArgs = excludes.map(d => `-not -path '*/${d}/*'`).join(" ");
20
+ const command = `find . -name '${pattern}' -type f ${excludeArgs} 2>/dev/null | head -${maxResults * 3}`;
21
+ const raw = await exec(command, cwd);
22
+ const allPaths = raw.split("\n").filter(l => l.trim());
23
+ // Categorize
24
+ const source = [];
25
+ const config = [];
26
+ const other = [];
27
+ const filteredCounts = {};
28
+ for (const path of allPaths) {
29
+ if (isExcludedDir(path)) {
30
+ const dir = DEFAULT_EXCLUDE_DIRS.find(d => path.includes(`/${d}/`)) ?? "other";
31
+ filteredCounts[dir] = (filteredCounts[dir] ?? 0) + 1;
32
+ continue;
33
+ }
34
+ if (isSourceFile(path)) {
35
+ source.push(path);
36
+ }
37
+ else if (path.match(/\.(json|yaml|yml|toml|ini|env)/)) {
38
+ config.push(path);
39
+ }
40
+ else {
41
+ other.push(path);
42
+ }
43
+ }
44
+ // Sort by relevance
45
+ source.sort((a, b) => relevanceScore(b) - relevanceScore(a));
46
+ // Limit results
47
+ const filtered = Object.entries(filteredCounts).map(([reason, count]) => ({ reason, count }));
48
+ // Estimate token savings
49
+ const rawTokens = Math.ceil(raw.length / 4);
50
+ const result = {
51
+ query: pattern,
52
+ total: allPaths.length,
53
+ source: source.slice(0, maxResults),
54
+ config: config.slice(0, 10),
55
+ other: other.slice(0, 10),
56
+ filtered,
57
+ };
58
+ const resultTokens = Math.ceil(JSON.stringify(result).length / 4);
59
+ result.tokensSaved = Math.max(0, rawTokens - resultTokens);
60
+ return result;
61
+ }
@@ -0,0 +1,34 @@
1
+ // Smart filters for search results — auto-hide noise, prioritize source files
2
+ export const DEFAULT_EXCLUDE_DIRS = [
3
+ "node_modules", ".git", "dist", "build", ".next", "__pycache__",
4
+ "coverage", ".turbo", ".cache", ".output", "vendor", "target",
5
+ ];
6
+ export const SOURCE_EXTENSIONS = new Set([
7
+ ".ts", ".tsx", ".js", ".jsx", ".py", ".go", ".rs", ".java", ".rb",
8
+ ".sh", ".c", ".cpp", ".h", ".css", ".scss", ".html", ".vue", ".svelte",
9
+ ".md", ".json", ".yaml", ".yml", ".toml", ".sql", ".graphql",
10
+ ]);
11
+ export const CONFIG_EXTENSIONS = new Set([
12
+ ".json", ".yaml", ".yml", ".toml", ".ini", ".env", ".config.js",
13
+ ".config.ts", ".config.mjs",
14
+ ]);
15
+ export function isSourceFile(path) {
16
+ const ext = path.match(/\.\w+$/)?.[0] ?? "";
17
+ return SOURCE_EXTENSIONS.has(ext);
18
+ }
19
+ export function isExcludedDir(path) {
20
+ return DEFAULT_EXCLUDE_DIRS.some(d => path.includes(`/${d}/`) || path.includes(`/${d}`));
21
+ }
22
+ /** Relevance score: higher = more relevant */
23
+ export function relevanceScore(path) {
24
+ if (isExcludedDir(path))
25
+ return 0;
26
+ const ext = path.match(/\.\w+$/)?.[0] ?? "";
27
+ if (SOURCE_EXTENSIONS.has(ext))
28
+ return 10;
29
+ if (CONFIG_EXTENSIONS.has(ext))
30
+ return 5;
31
+ if (path.includes("/test") || path.includes(".test.") || path.includes(".spec."))
32
+ return 7;
33
+ return 3;
34
+ }
@@ -0,0 +1,5 @@
1
+ // Smart search — unified entry point for file + content search
2
+ export { searchFiles } from "./file-search.js";
3
+ export { searchContent } from "./content-search.js";
4
+ export { DEFAULT_EXCLUDE_DIRS, SOURCE_EXTENSIONS, isSourceFile, isExcludedDir, relevanceScore } from "./filters.js";
5
+ export { semanticSearch, findExports, findComponents, findHooks } from "./semantic.js";
@@ -0,0 +1,320 @@
1
+ // Semantic code search — AST-powered search that understands code structure
2
+ // Instead of raw grep, searches by meaning: "find auth functions" → login(), verifyToken()
3
+ import { spawn } from "child_process";
4
+ import { readFileSync, existsSync } from "fs";
5
+ import { join } from "path";
6
+ function exec(command, cwd) {
7
+ return new Promise((resolve) => {
8
+ const proc = spawn("/bin/zsh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
9
+ let out = "";
10
+ proc.stdout?.on("data", (d) => { out += d.toString(); });
11
+ proc.stderr?.on("data", (d) => { });
12
+ proc.on("close", () => resolve(out));
13
+ });
14
+ }
15
+ /** Extract code symbols from a TypeScript/JavaScript file using regex-based parsing */
16
+ export function extractSymbolsFromFile(filePath) {
17
+ return extractSymbols(filePath);
18
+ }
19
+ /** Extract the complete code block for a symbol by name */
20
+ export function extractBlock(filePath, symbolName) {
21
+ if (!existsSync(filePath))
22
+ return null;
23
+ const content = readFileSync(filePath, "utf8");
24
+ const lines = content.split("\n");
25
+ const symbols = extractSymbols(filePath);
26
+ const symbol = symbols.find(s => s.name === symbolName && s.kind !== "import");
27
+ if (!symbol)
28
+ return null;
29
+ const startLine = symbol.line - 1; // 0-indexed
30
+ let braceDepth = 0;
31
+ let foundOpen = false;
32
+ let endLine = startLine;
33
+ for (let i = startLine; i < lines.length; i++) {
34
+ const line = lines[i];
35
+ for (const ch of line) {
36
+ if (ch === "{") {
37
+ braceDepth++;
38
+ foundOpen = true;
39
+ }
40
+ if (ch === "}") {
41
+ braceDepth--;
42
+ }
43
+ }
44
+ endLine = i;
45
+ if (foundOpen && braceDepth <= 0)
46
+ break;
47
+ // For single-line arrow functions without braces
48
+ if (i === startLine && !line.includes("{") && line.includes("=>"))
49
+ break;
50
+ }
51
+ return {
52
+ code: lines.slice(startLine, endLine + 1).join("\n"),
53
+ startLine: startLine + 1, // 1-indexed
54
+ endLine: endLine + 1,
55
+ };
56
+ }
57
+ function extractSymbols(filePath) {
58
+ if (!existsSync(filePath))
59
+ return [];
60
+ const content = readFileSync(filePath, "utf8");
61
+ const lines = content.split("\n");
62
+ const symbols = [];
63
+ const file = filePath;
64
+ const ext = filePath.match(/\.(\w+)$/)?.[1] ?? "";
65
+ // Python support
66
+ if (ext === "py") {
67
+ for (let i = 0; i < lines.length; i++) {
68
+ const line = lines[i];
69
+ const defMatch = line.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\(/);
70
+ if (defMatch) {
71
+ symbols.push({ name: defMatch[2], kind: "function", file, line: i + 1, signature: line.trim(), exported: !defMatch[2].startsWith("_") });
72
+ }
73
+ const classMatch = line.match(/^class\s+(\w+)/);
74
+ if (classMatch) {
75
+ symbols.push({ name: classMatch[1], kind: "class", file, line: i + 1, signature: line.trim(), exported: true });
76
+ }
77
+ }
78
+ return symbols;
79
+ }
80
+ // Go support
81
+ if (ext === "go") {
82
+ for (let i = 0; i < lines.length; i++) {
83
+ const line = lines[i];
84
+ const funcMatch = line.match(/^func\s+(?:\(\w+\s+\*?\w+\)\s+)?(\w+)\s*\(/);
85
+ if (funcMatch) {
86
+ symbols.push({ name: funcMatch[1], kind: "function", file, line: i + 1, signature: line.trim(), exported: /^[A-Z]/.test(funcMatch[1]) });
87
+ }
88
+ const typeMatch = line.match(/^type\s+(\w+)\s+(struct|interface)/);
89
+ if (typeMatch) {
90
+ symbols.push({ name: typeMatch[1], kind: typeMatch[2] === "interface" ? "interface" : "class", file, line: i + 1, signature: line.trim(), exported: /^[A-Z]/.test(typeMatch[1]) });
91
+ }
92
+ }
93
+ return symbols;
94
+ }
95
+ // Rust support
96
+ if (ext === "rs") {
97
+ for (let i = 0; i < lines.length; i++) {
98
+ const line = lines[i];
99
+ const fnMatch = line.match(/^\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/);
100
+ if (fnMatch) {
101
+ symbols.push({ name: fnMatch[1], kind: "function", file, line: i + 1, signature: line.trim(), exported: line.includes("pub") });
102
+ }
103
+ const structMatch = line.match(/^\s*(?:pub\s+)?struct\s+(\w+)/);
104
+ if (structMatch) {
105
+ symbols.push({ name: structMatch[1], kind: "class", file, line: i + 1, signature: line.trim(), exported: line.includes("pub") });
106
+ }
107
+ const enumMatch = line.match(/^\s*(?:pub\s+)?enum\s+(\w+)/);
108
+ if (enumMatch) {
109
+ symbols.push({ name: enumMatch[1], kind: "type", file, line: i + 1, signature: line.trim(), exported: line.includes("pub") });
110
+ }
111
+ const traitMatch = line.match(/^\s*(?:pub\s+)?trait\s+(\w+)/);
112
+ if (traitMatch) {
113
+ symbols.push({ name: traitMatch[1], kind: "interface", file, line: i + 1, signature: line.trim(), exported: line.includes("pub") });
114
+ }
115
+ }
116
+ return symbols;
117
+ }
118
+ // TypeScript/JavaScript (default)
119
+ for (let i = 0; i < lines.length; i++) {
120
+ const line = lines[i];
121
+ const lineNum = i + 1;
122
+ const isExported = line.trimStart().startsWith("export");
123
+ // Functions: export function X(...) or export const X = (...) =>
124
+ const funcMatch = line.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(/);
125
+ if (funcMatch) {
126
+ const prevLine = i > 0 ? lines[i - 1] : "";
127
+ const doc = prevLine.trim().startsWith("/**") || prevLine.trim().startsWith("//")
128
+ ? prevLine.trim().replace(/^\/\*\*\s*|\s*\*\/$/g, "").replace(/^\/\/\s*/, "")
129
+ : undefined;
130
+ symbols.push({
131
+ name: funcMatch[1], kind: "function", file, line: lineNum,
132
+ signature: line.trim().replace(/\{.*$/, "").trim(),
133
+ exported: isExported, doc,
134
+ });
135
+ continue;
136
+ }
137
+ // Arrow functions: export const X = (...) =>
138
+ const arrowMatch = line.match(/(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\(([^)]*)\)\s*(?::\s*\w[^=]*)?\s*=>/);
139
+ if (arrowMatch) {
140
+ // Detect React hooks
141
+ const isHook = arrowMatch[1].startsWith("use");
142
+ const isComponent = /^[A-Z]/.test(arrowMatch[1]);
143
+ symbols.push({
144
+ name: arrowMatch[1],
145
+ kind: isHook ? "hook" : isComponent ? "component" : "function",
146
+ file, line: lineNum,
147
+ signature: line.trim().replace(/\{.*$/, "").replace(/=>.*$/, "=>").trim(),
148
+ exported: isExported,
149
+ });
150
+ continue;
151
+ }
152
+ // Classes
153
+ const classMatch = line.match(/(?:export\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?/);
154
+ if (classMatch) {
155
+ symbols.push({
156
+ name: classMatch[1], kind: "class", file, line: lineNum,
157
+ signature: line.trim().replace(/\{.*$/, "").trim(),
158
+ exported: isExported,
159
+ });
160
+ continue;
161
+ }
162
+ // Interfaces
163
+ const ifaceMatch = line.match(/(?:export\s+)?interface\s+(\w+)/);
164
+ if (ifaceMatch) {
165
+ symbols.push({
166
+ name: ifaceMatch[1], kind: "interface", file, line: lineNum,
167
+ signature: line.trim().replace(/\{.*$/, "").trim(),
168
+ exported: isExported,
169
+ });
170
+ continue;
171
+ }
172
+ // Type aliases
173
+ const typeMatch = line.match(/(?:export\s+)?type\s+(\w+)\s*=/);
174
+ if (typeMatch) {
175
+ symbols.push({
176
+ name: typeMatch[1], kind: "type", file, line: lineNum,
177
+ signature: line.trim(),
178
+ exported: isExported,
179
+ });
180
+ continue;
181
+ }
182
+ // Imports (for dependency tracking)
183
+ const importMatch = line.match(/import\s+(?:\{([^}]+)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/);
184
+ if (importMatch) {
185
+ const names = importMatch[1]
186
+ ? importMatch[1].split(",").map(s => s.trim().split(" as ")[0].trim())
187
+ : [importMatch[2]];
188
+ for (const name of names) {
189
+ if (name) {
190
+ symbols.push({
191
+ name, kind: "import", file, line: lineNum,
192
+ signature: `from '${importMatch[3]}'`,
193
+ exported: false,
194
+ });
195
+ }
196
+ }
197
+ continue;
198
+ }
199
+ // Exported constants/variables
200
+ const constMatch = line.match(/export\s+const\s+(\w+)\s*[=:]/);
201
+ if (constMatch && !arrowMatch) {
202
+ symbols.push({
203
+ name: constMatch[1], kind: "variable", file, line: lineNum,
204
+ signature: line.trim().slice(0, 80),
205
+ exported: true,
206
+ });
207
+ }
208
+ }
209
+ return symbols;
210
+ }
211
+ /** Find all source files in a directory */
212
+ async function findSourceFiles(cwd, maxFiles = 200) {
213
+ const excludes = ["node_modules", ".git", "dist", "build", ".next", "coverage", "__pycache__"];
214
+ const excludeArgs = excludes.map(d => `-not -path '*/${d}/*'`).join(" ");
215
+ const extensions = "\\( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.jsx' \\)";
216
+ const cmd = `find . ${extensions} ${excludeArgs} -type f 2>/dev/null | head -${maxFiles}`;
217
+ const output = await exec(cmd, cwd);
218
+ return output.split("\n").filter(l => l.trim()).map(l => join(cwd, l.trim()));
219
+ }
220
+ /** Semantic search: find symbols matching a natural language query */
221
+ export async function semanticSearch(query, cwd, options = {}) {
222
+ const { kinds, exportedOnly = false, maxResults = 30 } = options;
223
+ // Find all source files
224
+ const files = await findSourceFiles(cwd);
225
+ // Extract symbols from all files
226
+ let allSymbols = [];
227
+ for (const file of files) {
228
+ try {
229
+ allSymbols.push(...extractSymbols(file));
230
+ }
231
+ catch { /* skip unreadable files */ }
232
+ }
233
+ // Filter by kind
234
+ if (kinds) {
235
+ allSymbols = allSymbols.filter(s => kinds.includes(s.kind));
236
+ }
237
+ // Filter by exported
238
+ if (exportedOnly) {
239
+ allSymbols = allSymbols.filter(s => s.exported);
240
+ }
241
+ // Score each symbol against the query
242
+ const queryLower = query.toLowerCase();
243
+ const queryWords = queryLower.split(/\s+/).filter(w => w.length > 2);
244
+ const scored = allSymbols.map(symbol => {
245
+ let score = 0;
246
+ const nameLower = symbol.name.toLowerCase();
247
+ const sigLower = (symbol.signature ?? "").toLowerCase();
248
+ const fileLower = symbol.file.toLowerCase();
249
+ // Exact name match
250
+ if (queryWords.some(w => nameLower === w))
251
+ score += 10;
252
+ // Name contains query word
253
+ if (queryWords.some(w => nameLower.includes(w)))
254
+ score += 5;
255
+ // Signature contains query word
256
+ if (queryWords.some(w => sigLower.includes(w)))
257
+ score += 3;
258
+ // File path contains query word
259
+ if (queryWords.some(w => fileLower.includes(w)))
260
+ score += 2;
261
+ // Doc contains query word
262
+ if (symbol.doc && queryWords.some(w => symbol.doc.toLowerCase().includes(w)))
263
+ score += 4;
264
+ // Boost exported symbols
265
+ if (symbol.exported)
266
+ score += 1;
267
+ // Boost functions/classes over imports
268
+ if (symbol.kind === "function" || symbol.kind === "class")
269
+ score += 1;
270
+ // Semantic matching for common patterns
271
+ if (queryLower.includes("component") && symbol.kind === "component")
272
+ score += 5;
273
+ if (queryLower.includes("hook") && symbol.kind === "hook")
274
+ score += 5;
275
+ if (queryLower.includes("type") && (symbol.kind === "type" || symbol.kind === "interface"))
276
+ score += 5;
277
+ if (queryLower.includes("import") && symbol.kind === "import")
278
+ score += 5;
279
+ if (queryLower.includes("class") && symbol.kind === "class")
280
+ score += 5;
281
+ return { symbol, score };
282
+ });
283
+ // Sort by score, filter zero scores
284
+ const results = scored
285
+ .filter(s => s.score > 0)
286
+ .sort((a, b) => b.score - a.score)
287
+ .slice(0, maxResults)
288
+ .map(s => s.symbol);
289
+ // Make file paths relative
290
+ for (const r of results) {
291
+ if (r.file.startsWith(cwd)) {
292
+ r.file = "." + r.file.slice(cwd.length);
293
+ }
294
+ }
295
+ // Estimate token savings
296
+ const rawGrep = await exec(`grep -rn '${queryWords[0] ?? query}' . --include='*.ts' --include='*.tsx' 2>/dev/null | head -100`, cwd);
297
+ const rawTokens = Math.ceil(rawGrep.length / 4);
298
+ const resultTokens = Math.ceil(JSON.stringify(results).length / 4);
299
+ return {
300
+ query,
301
+ symbols: results,
302
+ totalFiles: files.length,
303
+ tokensSaved: Math.max(0, rawTokens - resultTokens),
304
+ };
305
+ }
306
+ /** Quick helper: find all exported functions */
307
+ export async function findExports(cwd) {
308
+ const result = await semanticSearch("export", cwd, { exportedOnly: true, maxResults: 100 });
309
+ return result.symbols;
310
+ }
311
+ /** Quick helper: find all React components */
312
+ export async function findComponents(cwd) {
313
+ const result = await semanticSearch("component", cwd, { kinds: ["component"], maxResults: 50 });
314
+ return result.symbols;
315
+ }
316
+ /** Quick helper: find all hooks */
317
+ export async function findHooks(cwd) {
318
+ const result = await semanticSearch("hook", cwd, { kinds: ["hook"], maxResults: 50 });
319
+ return result.symbols;
320
+ }
@@ -0,0 +1,59 @@
1
+ // Session boot cache — precompute common data on first MCP call
2
+ // Agents always start with git status + file tree + package.json — do it once
3
+ import { spawn } from "child_process";
4
+ import { existsSync, readFileSync } from "fs";
5
+ import { join } from "path";
6
+ let bootCache = null;
7
+ let bootCwd = "";
8
+ function exec(command, cwd) {
9
+ return new Promise((resolve) => {
10
+ const proc = spawn("/bin/zsh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
11
+ let out = "";
12
+ proc.stdout?.on("data", (d) => { out += d.toString(); });
13
+ proc.on("close", () => resolve(out.trim()));
14
+ });
15
+ }
16
+ /** Get or build session boot context */
17
+ export async function getBootContext(cwd) {
18
+ if (bootCache && bootCwd === cwd)
19
+ return bootCache;
20
+ const [branch, status, log, srcLs] = await Promise.all([
21
+ exec("git branch --show-current 2>/dev/null", cwd),
22
+ exec("git status --porcelain 2>/dev/null", cwd),
23
+ exec("git log --oneline -8 2>/dev/null", cwd),
24
+ exec("ls -1 src/ 2>/dev/null || ls -1 lib/ 2>/dev/null || echo ''", cwd),
25
+ ]);
26
+ let pkg = null;
27
+ const pkgPath = join(cwd, "package.json");
28
+ if (existsSync(pkgPath)) {
29
+ try {
30
+ pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
31
+ }
32
+ catch { }
33
+ }
34
+ bootCache = {
35
+ cwd,
36
+ git: {
37
+ branch: branch || null,
38
+ dirty: status.length > 0,
39
+ changedFiles: status.split("\n").filter(l => l.trim()).length,
40
+ recentCommits: log.split("\n").filter(l => l.trim()).slice(0, 5).map(l => {
41
+ const m = l.match(/^([a-f0-9]+)\s+(.+)$/);
42
+ return m ? { hash: m[1], message: m[2] } : null;
43
+ }).filter(Boolean),
44
+ },
45
+ project: pkg ? {
46
+ name: pkg.name,
47
+ version: pkg.version,
48
+ scripts: pkg.scripts ? Object.keys(pkg.scripts) : [],
49
+ deps: pkg.dependencies ? Object.keys(pkg.dependencies).length : 0,
50
+ } : null,
51
+ sourceFiles: srcLs.split("\n").filter(l => l.trim()),
52
+ };
53
+ bootCwd = cwd;
54
+ return bootCache;
55
+ }
56
+ /** Invalidate boot cache (call after git operations or file changes) */
57
+ export function invalidateBootCache() {
58
+ bootCache = null;
59
+ }
@@ -0,0 +1,55 @@
1
+ // Session context — stores last N command+output pairs for follow-up queries
2
+ // Enables: terminal "show auth code" → terminal "explain that function"
3
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
4
+ import { homedir } from "os";
5
+ import { join } from "path";
6
+ const DIR = join(homedir(), ".terminal");
7
+ const CTX_FILE = join(DIR, "session-context.json");
8
+ const MAX_ENTRIES = 5;
9
+ function ensureDir() {
10
+ if (!existsSync(DIR))
11
+ mkdirSync(DIR, { recursive: true });
12
+ }
13
+ /** Load session context */
14
+ export function loadContext() {
15
+ ensureDir();
16
+ if (!existsSync(CTX_FILE))
17
+ return [];
18
+ try {
19
+ const entries = JSON.parse(readFileSync(CTX_FILE, "utf8"));
20
+ // Only return entries from last 30 minutes (session freshness)
21
+ const cutoff = Date.now() - 30 * 60 * 1000;
22
+ return entries.filter(e => e.timestamp > cutoff).slice(-MAX_ENTRIES);
23
+ }
24
+ catch {
25
+ return [];
26
+ }
27
+ }
28
+ /** Save a command to session context */
29
+ export function saveContext(prompt, command, output) {
30
+ ensureDir();
31
+ const entries = loadContext();
32
+ entries.push({
33
+ prompt,
34
+ command,
35
+ output: output.slice(0, 500),
36
+ timestamp: Date.now(),
37
+ });
38
+ // Keep only last N
39
+ const trimmed = entries.slice(-MAX_ENTRIES);
40
+ writeFileSync(CTX_FILE, JSON.stringify(trimmed, null, 2));
41
+ }
42
+ /** Format context for AI prompt injection */
43
+ export function formatContext() {
44
+ const entries = loadContext();
45
+ if (entries.length === 0)
46
+ return "";
47
+ const lines = ["\nRECENT SESSION CONTEXT (for follow-up references like 'that', 'it', 'the same'):"];
48
+ for (const e of entries.slice(-3)) {
49
+ lines.push(`> ${e.prompt}`);
50
+ lines.push(`$ ${e.command}`);
51
+ if (e.output)
52
+ lines.push(e.output.slice(0, 200));
53
+ }
54
+ return lines.join("\n");
55
+ }