@hasna/terminal 2.3.0 → 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 (267) 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/cli.js +64 -16
  10. package/dist/command-rewriter.js +64 -0
  11. package/dist/command-validator.js +86 -0
  12. package/dist/compression.js +107 -0
  13. package/dist/context-hints.js +275 -0
  14. package/dist/diff-cache.js +107 -0
  15. package/dist/discover.js +212 -0
  16. package/dist/economy.js +123 -0
  17. package/dist/expand-store.js +38 -0
  18. package/dist/file-cache.js +72 -0
  19. package/dist/file-index.js +62 -0
  20. package/dist/history.js +62 -0
  21. package/dist/lazy-executor.js +54 -0
  22. package/dist/line-dedup.js +59 -0
  23. package/dist/loop-detector.js +75 -0
  24. package/dist/mcp/install.js +98 -0
  25. package/dist/mcp/server.js +569 -0
  26. package/dist/noise-filter.js +86 -0
  27. package/dist/output-processor.js +129 -0
  28. package/dist/output-router.js +41 -0
  29. package/dist/output-store.js +111 -0
  30. package/dist/parsers/base.js +2 -0
  31. package/dist/parsers/build.js +64 -0
  32. package/dist/parsers/errors.js +101 -0
  33. package/dist/parsers/files.js +78 -0
  34. package/dist/parsers/git.js +99 -0
  35. package/dist/parsers/index.js +48 -0
  36. package/dist/parsers/tests.js +89 -0
  37. package/dist/providers/anthropic.js +39 -0
  38. package/dist/providers/base.js +4 -0
  39. package/dist/providers/cerebras.js +95 -0
  40. package/dist/providers/groq.js +95 -0
  41. package/dist/providers/index.js +73 -0
  42. package/dist/providers/xai.js +95 -0
  43. package/dist/recipes/model.js +20 -0
  44. package/dist/recipes/storage.js +136 -0
  45. package/dist/search/content-search.js +68 -0
  46. package/dist/search/file-search.js +61 -0
  47. package/dist/search/filters.js +34 -0
  48. package/dist/search/index.js +5 -0
  49. package/dist/search/semantic.js +320 -0
  50. package/dist/session-boot.js +59 -0
  51. package/dist/session-context.js +55 -0
  52. package/dist/sessions-db.js +173 -0
  53. package/dist/smart-display.js +286 -0
  54. package/dist/snapshots.js +51 -0
  55. package/dist/supervisor.js +112 -0
  56. package/dist/test-watchlist.js +131 -0
  57. package/dist/tool-profiles.js +122 -0
  58. package/dist/tree.js +94 -0
  59. package/dist/usage-cache.js +65 -0
  60. package/package.json +8 -1
  61. package/src/ai.ts +8 -0
  62. package/src/cli.tsx +57 -18
  63. package/src/output-processor.ts +6 -1
  64. package/src/output-store.ts +58 -12
  65. package/src/tool-profiles.ts +139 -0
  66. package/.claude/scheduled_tasks.lock +0 -1
  67. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -20
  68. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -14
  69. package/CONTRIBUTING.md +0 -80
  70. package/benchmarks/benchmark.mjs +0 -115
  71. package/imported_modules.txt +0 -0
  72. package/temp/rtk/.claude/agents/code-reviewer.md +0 -221
  73. package/temp/rtk/.claude/agents/debugger.md +0 -519
  74. package/temp/rtk/.claude/agents/rtk-testing-specialist.md +0 -461
  75. package/temp/rtk/.claude/agents/rust-rtk.md +0 -511
  76. package/temp/rtk/.claude/agents/technical-writer.md +0 -355
  77. package/temp/rtk/.claude/commands/diagnose.md +0 -352
  78. package/temp/rtk/.claude/commands/test-routing.md +0 -362
  79. package/temp/rtk/.claude/hooks/bash/pre-commit-format.sh +0 -16
  80. package/temp/rtk/.claude/hooks/rtk-rewrite.sh +0 -70
  81. package/temp/rtk/.claude/hooks/rtk-suggest.sh +0 -152
  82. package/temp/rtk/.claude/rules/cli-testing.md +0 -526
  83. package/temp/rtk/.claude/skills/issue-triage/SKILL.md +0 -348
  84. package/temp/rtk/.claude/skills/issue-triage/templates/issue-comment.md +0 -134
  85. package/temp/rtk/.claude/skills/performance.md +0 -435
  86. package/temp/rtk/.claude/skills/pr-triage/SKILL.md +0 -315
  87. package/temp/rtk/.claude/skills/pr-triage/templates/review-comment.md +0 -71
  88. package/temp/rtk/.claude/skills/repo-recap.md +0 -206
  89. package/temp/rtk/.claude/skills/rtk-tdd/SKILL.md +0 -78
  90. package/temp/rtk/.claude/skills/rtk-tdd/references/testing-patterns.md +0 -124
  91. package/temp/rtk/.claude/skills/security-guardian.md +0 -503
  92. package/temp/rtk/.claude/skills/ship.md +0 -404
  93. package/temp/rtk/.github/workflows/benchmark.yml +0 -34
  94. package/temp/rtk/.github/workflows/dco-check.yaml +0 -12
  95. package/temp/rtk/.github/workflows/release-please.yml +0 -51
  96. package/temp/rtk/.github/workflows/release.yml +0 -343
  97. package/temp/rtk/.github/workflows/security-check.yml +0 -135
  98. package/temp/rtk/.github/workflows/validate-docs.yml +0 -78
  99. package/temp/rtk/.release-please-manifest.json +0 -3
  100. package/temp/rtk/ARCHITECTURE.md +0 -1491
  101. package/temp/rtk/CHANGELOG.md +0 -640
  102. package/temp/rtk/CLAUDE.md +0 -605
  103. package/temp/rtk/CONTRIBUTING.md +0 -199
  104. package/temp/rtk/Cargo.lock +0 -1668
  105. package/temp/rtk/Cargo.toml +0 -64
  106. package/temp/rtk/Formula/rtk.rb +0 -43
  107. package/temp/rtk/INSTALL.md +0 -390
  108. package/temp/rtk/LICENSE +0 -21
  109. package/temp/rtk/README.md +0 -386
  110. package/temp/rtk/README_es.md +0 -159
  111. package/temp/rtk/README_fr.md +0 -197
  112. package/temp/rtk/README_ja.md +0 -159
  113. package/temp/rtk/README_ko.md +0 -159
  114. package/temp/rtk/README_zh.md +0 -167
  115. package/temp/rtk/ROADMAP.md +0 -15
  116. package/temp/rtk/SECURITY.md +0 -217
  117. package/temp/rtk/TEST_EXEC_TIME.md +0 -102
  118. package/temp/rtk/build.rs +0 -57
  119. package/temp/rtk/docs/AUDIT_GUIDE.md +0 -432
  120. package/temp/rtk/docs/FEATURES.md +0 -1410
  121. package/temp/rtk/docs/TROUBLESHOOTING.md +0 -309
  122. package/temp/rtk/docs/filter-workflow.md +0 -102
  123. package/temp/rtk/docs/images/gain-dashboard.jpg +0 -0
  124. package/temp/rtk/docs/tracking.md +0 -583
  125. package/temp/rtk/hooks/opencode-rtk.ts +0 -39
  126. package/temp/rtk/hooks/rtk-awareness.md +0 -29
  127. package/temp/rtk/hooks/rtk-rewrite.sh +0 -61
  128. package/temp/rtk/hooks/test-rtk-rewrite.sh +0 -442
  129. package/temp/rtk/install.sh +0 -124
  130. package/temp/rtk/release-please-config.json +0 -10
  131. package/temp/rtk/scripts/benchmark.sh +0 -592
  132. package/temp/rtk/scripts/check-installation.sh +0 -162
  133. package/temp/rtk/scripts/install-local.sh +0 -37
  134. package/temp/rtk/scripts/rtk-economics.sh +0 -137
  135. package/temp/rtk/scripts/test-all.sh +0 -561
  136. package/temp/rtk/scripts/test-aristote.sh +0 -227
  137. package/temp/rtk/scripts/test-tracking.sh +0 -79
  138. package/temp/rtk/scripts/update-readme-metrics.sh +0 -32
  139. package/temp/rtk/scripts/validate-docs.sh +0 -73
  140. package/temp/rtk/src/aws_cmd.rs +0 -880
  141. package/temp/rtk/src/binlog.rs +0 -1645
  142. package/temp/rtk/src/cargo_cmd.rs +0 -1727
  143. package/temp/rtk/src/cc_economics.rs +0 -1157
  144. package/temp/rtk/src/ccusage.rs +0 -340
  145. package/temp/rtk/src/config.rs +0 -187
  146. package/temp/rtk/src/container.rs +0 -855
  147. package/temp/rtk/src/curl_cmd.rs +0 -134
  148. package/temp/rtk/src/deps.rs +0 -268
  149. package/temp/rtk/src/diff_cmd.rs +0 -367
  150. package/temp/rtk/src/discover/mod.rs +0 -274
  151. package/temp/rtk/src/discover/provider.rs +0 -388
  152. package/temp/rtk/src/discover/registry.rs +0 -2022
  153. package/temp/rtk/src/discover/report.rs +0 -202
  154. package/temp/rtk/src/discover/rules.rs +0 -667
  155. package/temp/rtk/src/display_helpers.rs +0 -402
  156. package/temp/rtk/src/dotnet_cmd.rs +0 -1771
  157. package/temp/rtk/src/dotnet_format_report.rs +0 -133
  158. package/temp/rtk/src/dotnet_trx.rs +0 -593
  159. package/temp/rtk/src/env_cmd.rs +0 -204
  160. package/temp/rtk/src/filter.rs +0 -462
  161. package/temp/rtk/src/filters/README.md +0 -52
  162. package/temp/rtk/src/filters/ansible-playbook.toml +0 -34
  163. package/temp/rtk/src/filters/basedpyright.toml +0 -47
  164. package/temp/rtk/src/filters/biome.toml +0 -45
  165. package/temp/rtk/src/filters/brew-install.toml +0 -37
  166. package/temp/rtk/src/filters/composer-install.toml +0 -40
  167. package/temp/rtk/src/filters/df.toml +0 -16
  168. package/temp/rtk/src/filters/dotnet-build.toml +0 -64
  169. package/temp/rtk/src/filters/du.toml +0 -16
  170. package/temp/rtk/src/filters/fail2ban-client.toml +0 -15
  171. package/temp/rtk/src/filters/gcc.toml +0 -49
  172. package/temp/rtk/src/filters/gcloud.toml +0 -22
  173. package/temp/rtk/src/filters/hadolint.toml +0 -24
  174. package/temp/rtk/src/filters/helm.toml +0 -29
  175. package/temp/rtk/src/filters/iptables.toml +0 -27
  176. package/temp/rtk/src/filters/jj.toml +0 -28
  177. package/temp/rtk/src/filters/jq.toml +0 -24
  178. package/temp/rtk/src/filters/make.toml +0 -41
  179. package/temp/rtk/src/filters/markdownlint.toml +0 -24
  180. package/temp/rtk/src/filters/mix-compile.toml +0 -27
  181. package/temp/rtk/src/filters/mix-format.toml +0 -15
  182. package/temp/rtk/src/filters/mvn-build.toml +0 -44
  183. package/temp/rtk/src/filters/oxlint.toml +0 -43
  184. package/temp/rtk/src/filters/ping.toml +0 -63
  185. package/temp/rtk/src/filters/pio-run.toml +0 -40
  186. package/temp/rtk/src/filters/poetry-install.toml +0 -50
  187. package/temp/rtk/src/filters/pre-commit.toml +0 -35
  188. package/temp/rtk/src/filters/ps.toml +0 -16
  189. package/temp/rtk/src/filters/quarto-render.toml +0 -41
  190. package/temp/rtk/src/filters/rsync.toml +0 -48
  191. package/temp/rtk/src/filters/shellcheck.toml +0 -27
  192. package/temp/rtk/src/filters/shopify-theme.toml +0 -29
  193. package/temp/rtk/src/filters/skopeo.toml +0 -45
  194. package/temp/rtk/src/filters/sops.toml +0 -16
  195. package/temp/rtk/src/filters/ssh.toml +0 -44
  196. package/temp/rtk/src/filters/stat.toml +0 -34
  197. package/temp/rtk/src/filters/swift-build.toml +0 -41
  198. package/temp/rtk/src/filters/systemctl-status.toml +0 -33
  199. package/temp/rtk/src/filters/terraform-plan.toml +0 -35
  200. package/temp/rtk/src/filters/tofu-fmt.toml +0 -16
  201. package/temp/rtk/src/filters/tofu-init.toml +0 -38
  202. package/temp/rtk/src/filters/tofu-plan.toml +0 -35
  203. package/temp/rtk/src/filters/tofu-validate.toml +0 -17
  204. package/temp/rtk/src/filters/trunk-build.toml +0 -39
  205. package/temp/rtk/src/filters/ty.toml +0 -50
  206. package/temp/rtk/src/filters/uv-sync.toml +0 -37
  207. package/temp/rtk/src/filters/xcodebuild.toml +0 -99
  208. package/temp/rtk/src/filters/yamllint.toml +0 -25
  209. package/temp/rtk/src/find_cmd.rs +0 -598
  210. package/temp/rtk/src/format_cmd.rs +0 -386
  211. package/temp/rtk/src/gain.rs +0 -723
  212. package/temp/rtk/src/gh_cmd.rs +0 -1651
  213. package/temp/rtk/src/git.rs +0 -2012
  214. package/temp/rtk/src/go_cmd.rs +0 -592
  215. package/temp/rtk/src/golangci_cmd.rs +0 -254
  216. package/temp/rtk/src/grep_cmd.rs +0 -288
  217. package/temp/rtk/src/gt_cmd.rs +0 -810
  218. package/temp/rtk/src/hook_audit_cmd.rs +0 -283
  219. package/temp/rtk/src/hook_check.rs +0 -171
  220. package/temp/rtk/src/init.rs +0 -1859
  221. package/temp/rtk/src/integrity.rs +0 -537
  222. package/temp/rtk/src/json_cmd.rs +0 -231
  223. package/temp/rtk/src/learn/detector.rs +0 -628
  224. package/temp/rtk/src/learn/mod.rs +0 -119
  225. package/temp/rtk/src/learn/report.rs +0 -184
  226. package/temp/rtk/src/lint_cmd.rs +0 -694
  227. package/temp/rtk/src/local_llm.rs +0 -316
  228. package/temp/rtk/src/log_cmd.rs +0 -248
  229. package/temp/rtk/src/ls.rs +0 -324
  230. package/temp/rtk/src/main.rs +0 -2482
  231. package/temp/rtk/src/mypy_cmd.rs +0 -389
  232. package/temp/rtk/src/next_cmd.rs +0 -241
  233. package/temp/rtk/src/npm_cmd.rs +0 -236
  234. package/temp/rtk/src/parser/README.md +0 -267
  235. package/temp/rtk/src/parser/error.rs +0 -46
  236. package/temp/rtk/src/parser/formatter.rs +0 -336
  237. package/temp/rtk/src/parser/mod.rs +0 -311
  238. package/temp/rtk/src/parser/types.rs +0 -119
  239. package/temp/rtk/src/pip_cmd.rs +0 -302
  240. package/temp/rtk/src/playwright_cmd.rs +0 -479
  241. package/temp/rtk/src/pnpm_cmd.rs +0 -573
  242. package/temp/rtk/src/prettier_cmd.rs +0 -221
  243. package/temp/rtk/src/prisma_cmd.rs +0 -482
  244. package/temp/rtk/src/psql_cmd.rs +0 -382
  245. package/temp/rtk/src/pytest_cmd.rs +0 -384
  246. package/temp/rtk/src/read.rs +0 -217
  247. package/temp/rtk/src/rewrite_cmd.rs +0 -50
  248. package/temp/rtk/src/ruff_cmd.rs +0 -402
  249. package/temp/rtk/src/runner.rs +0 -271
  250. package/temp/rtk/src/summary.rs +0 -297
  251. package/temp/rtk/src/tee.rs +0 -405
  252. package/temp/rtk/src/telemetry.rs +0 -248
  253. package/temp/rtk/src/toml_filter.rs +0 -1655
  254. package/temp/rtk/src/tracking.rs +0 -1416
  255. package/temp/rtk/src/tree.rs +0 -209
  256. package/temp/rtk/src/tsc_cmd.rs +0 -259
  257. package/temp/rtk/src/utils.rs +0 -432
  258. package/temp/rtk/src/verify_cmd.rs +0 -47
  259. package/temp/rtk/src/vitest_cmd.rs +0 -385
  260. package/temp/rtk/src/wc_cmd.rs +0 -401
  261. package/temp/rtk/src/wget_cmd.rs +0 -260
  262. package/temp/rtk/tests/fixtures/dotnet/build_failed.txt +0 -11
  263. package/temp/rtk/tests/fixtures/dotnet/format_changes.json +0 -31
  264. package/temp/rtk/tests/fixtures/dotnet/format_empty.json +0 -1
  265. package/temp/rtk/tests/fixtures/dotnet/format_success.json +0 -12
  266. package/temp/rtk/tests/fixtures/dotnet/test_failed.txt +0 -18
  267. 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
+ }