@arhan-w/ibex 0.0.0-stage → 3.6.1

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 (167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +306 -2
  3. package/npm-package/LICENSE +21 -0
  4. package/npm-package/README.md +178 -0
  5. package/npm-package/bin/goat.js +3 -0
  6. package/npm-package/bin/ibex.js +78 -0
  7. package/npm-package/package.json +58 -0
  8. package/npm-package/scripts/install-binary.js +168 -0
  9. package/package.json +69 -6
  10. package/src/agent.ts +695 -0
  11. package/src/agents/loader.ts +110 -0
  12. package/src/ambient.d.ts +2 -0
  13. package/src/code/extract.ts +292 -0
  14. package/src/code/find.ts +244 -0
  15. package/src/code/grammars.ts +88 -0
  16. package/src/code/indexer.ts +242 -0
  17. package/src/code/semantic.ts +253 -0
  18. package/src/code/slash.ts +88 -0
  19. package/src/code/tool.ts +40 -0
  20. package/src/collab/client.ts +141 -0
  21. package/src/collab/handlers.ts +141 -0
  22. package/src/collab/invite.ts +39 -0
  23. package/src/collab/relay.ts +106 -0
  24. package/src/collab/sync.ts +131 -0
  25. package/src/commands.tsx +943 -0
  26. package/src/computer.ts +629 -0
  27. package/src/config.ts +318 -0
  28. package/src/constants.ts +18 -0
  29. package/src/context.ts +73 -0
  30. package/src/data/providers.json +2342 -0
  31. package/src/diff.ts +50 -0
  32. package/src/doctor.ts +443 -0
  33. package/src/errors.ts +139 -0
  34. package/src/gflash.ts +170 -0
  35. package/src/hooks.ts +133 -0
  36. package/src/ide/assets.gen.ts +3 -0
  37. package/src/ide/index.html +844 -0
  38. package/src/ide/server.ts +506 -0
  39. package/src/ide/vendor/marked.umd.js +80 -0
  40. package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
  41. package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
  42. package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
  43. package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
  44. package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
  45. package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
  46. package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
  47. package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
  48. package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
  49. package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
  50. package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
  51. package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
  52. package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
  53. package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
  54. package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
  55. package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
  56. package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
  57. package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
  58. package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
  59. package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
  60. package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
  61. package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
  62. package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
  63. package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
  64. package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
  65. package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
  66. package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
  67. package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
  68. package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
  69. package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
  70. package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
  71. package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
  72. package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
  73. package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
  74. package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
  75. package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
  76. package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
  77. package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
  78. package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
  79. package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
  80. package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
  81. package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
  82. package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
  83. package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
  84. package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
  85. package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
  86. package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
  87. package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
  88. package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
  89. package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
  90. package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
  91. package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
  92. package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
  93. package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
  94. package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
  95. package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
  96. package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
  97. package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
  98. package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
  99. package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
  100. package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
  101. package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
  102. package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
  103. package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
  104. package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
  105. package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
  106. package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
  107. package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
  108. package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
  109. package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
  110. package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
  111. package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
  112. package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
  113. package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
  114. package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
  115. package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
  116. package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
  117. package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
  118. package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
  119. package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
  120. package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
  121. package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
  122. package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
  123. package/src/ide/vendor/vs/editor/editor.main.css +8 -0
  124. package/src/ide/vendor/vs/editor/editor.main.js +798 -0
  125. package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
  126. package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
  127. package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
  128. package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
  129. package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
  130. package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
  131. package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
  132. package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
  133. package/src/ide/vendor/vs/loader.js +11 -0
  134. package/src/index-shared.ts +117 -0
  135. package/src/index.ts +586 -0
  136. package/src/llm.ts +721 -0
  137. package/src/logger.ts +39 -0
  138. package/src/mcp/client.ts +121 -0
  139. package/src/mcp/types.ts +27 -0
  140. package/src/oauth.ts +205 -0
  141. package/src/onboarding.ts +140 -0
  142. package/src/palette.tsx +199 -0
  143. package/src/permissions.ts +123 -0
  144. package/src/plugins/loader.ts +120 -0
  145. package/src/plugins/marketplace.ts +252 -0
  146. package/src/plugins/sandbox.ts +303 -0
  147. package/src/plugins/tar.ts +241 -0
  148. package/src/pricing.ts +78 -0
  149. package/src/protocol/client.ts +102 -0
  150. package/src/protocol/rpc.ts +43 -0
  151. package/src/protocol/serve.ts +136 -0
  152. package/src/providers.ts +402 -0
  153. package/src/rate-limiter.ts +101 -0
  154. package/src/refs.ts +97 -0
  155. package/src/runtime.ts +144 -0
  156. package/src/session.ts +401 -0
  157. package/src/skills/loader.ts +136 -0
  158. package/src/statusline.ts +70 -0
  159. package/src/system-prompt.ts +28 -0
  160. package/src/tools.ts +1280 -0
  161. package/src/tui.tsx +1355 -0
  162. package/src/update.ts +236 -0
  163. package/src/vendor/flashServer.ts +2 -0
  164. package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
  165. package/src/virtual-list.tsx +125 -0
  166. package/src/window.ts +31 -0
  167. package/tsconfig.json +16 -0
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Custom subagents — user-defined agent types loadable as `task` subagent_type.
3
+ *
4
+ * Agents are AGENT.md files (or .md files with frontmatter) in (highest
5
+ * priority first — a name defined in several roots uses the first hit):
6
+ * ./.goat/agents/<name>.md
7
+ * ./agents/<name>.md
8
+ * ~/.goatcode/agents/<name>.md
9
+ *
10
+ * Frontmatter fields:
11
+ * name — the subagent_type id (defaults to the filename)
12
+ * description — one-liner shown in the system prompt so the model knows
13
+ * when to pick this agent
14
+ * tools — comma-separated allowlist; omit = all tools. A tool not
15
+ * in the list is refused at dispatch (agent guardrail).
16
+ * model — optional model override for this agent
17
+ *
18
+ * The markdown body is the agent's system prompt — its persona, rules and
19
+ * output format. It is injected as extra system context on top of the base
20
+ * prompt for every turn the subagent runs.
21
+ */
22
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { appDir } from "../config.ts";
25
+
26
+ export interface AgentDef {
27
+ name: string;
28
+ description: string;
29
+ /** Tool allowlist; undefined/empty = all tools. */
30
+ tools?: string[];
31
+ /** Optional model override (provider/model). */
32
+ model?: string;
33
+ /** The markdown body — the agent's system prompt. */
34
+ body: string;
35
+ /** Where it was loaded from (for /agents listing). */
36
+ _path?: string;
37
+ }
38
+
39
+ interface AgentFrontmatter {
40
+ name?: string;
41
+ description?: string;
42
+ tools?: string[];
43
+ model?: string;
44
+ }
45
+
46
+ function parseFrontmatter(text: string): { fm: AgentFrontmatter; body: string } {
47
+ const fm: AgentFrontmatter = {};
48
+ let body = text;
49
+ const m = text.match(/^---\s*\n([\s\S]*?)\n---/);
50
+ if (m) {
51
+ body = text.slice(m[0].length).trimStart();
52
+ for (const line of m[1].trim().split("\n")) {
53
+ const i = line.indexOf(":");
54
+ if (i <= 0) continue;
55
+ const key = line.slice(0, i).trim();
56
+ const val = line.slice(i + 1).trim().replace(/^"|"$/g, "");
57
+ switch (key) {
58
+ case "name": fm.name = val; break;
59
+ case "description": fm.description = val; break;
60
+ case "tools": case "allowedTools": case "allowed-tools":
61
+ fm.tools = val.split(",").map((s) => s.trim()).filter(Boolean);
62
+ break;
63
+ case "model": fm.model = val; break;
64
+ }
65
+ }
66
+ }
67
+ return { fm, body };
68
+ }
69
+
70
+ export function loadCustomAgents(...roots: string[]): AgentDef[] {
71
+ const agents: AgentDef[] = [];
72
+ const seen = new Set<string>();
73
+ for (const root of roots) {
74
+ if (!existsSync(root)) continue;
75
+ for (const f of readdirSync(root)) {
76
+ if (!f.endsWith(".md")) continue;
77
+ try {
78
+ const text = readFileSync(join(root, f), "utf8");
79
+ const { fm, body } = parseFrontmatter(text);
80
+ const name = fm.name ?? f.replace(/\.md$/, "");
81
+ if (!fm.description) continue; // a .md without description isn't an agent
82
+ if (seen.has(name)) continue;
83
+ seen.add(name);
84
+ agents.push({ name, description: fm.description, tools: fm.tools, model: fm.model, body, _path: join(root, f) });
85
+ } catch { /* unreadable file — skip */ }
86
+ }
87
+ }
88
+ return agents;
89
+ }
90
+
91
+ /** Default agent search paths, highest priority first: project beats user.
92
+ * When the same agent name exists in several roots, the first root wins. */
93
+ export function agentDirs(cwd: string): string[] {
94
+ return [
95
+ join(cwd, ".goat", "agents"),
96
+ join(cwd, "agents"),
97
+ join(appDir(), "agents"),
98
+ ];
99
+ }
100
+
101
+ /**
102
+ * The system-prompt block describing custom agents, or "" when none exist.
103
+ * Tells the model which subagent_type values exist and when to use each.
104
+ */
105
+ export function customAgentsPrompt(agents: AgentDef[]): string {
106
+ if (!agents.length) return "";
107
+ const lines = agents.map((a) =>
108
+ `- ${a.name}: ${a.description}${a.tools?.length ? ` (tools: ${a.tools.join(", ")})` : ""}`);
109
+ return `Custom subagents available via task subagent_type:\n${lines}\nPick one when its description matches the work; otherwise use "general" or "explore".`;
110
+ }
@@ -0,0 +1,2 @@
1
+ declare module "onnxruntime-node";
2
+ declare module "@xenova/transformers";
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Symbol/import/call extraction per source file: tree-sitter when a grammar
3
+ * wasm resolves, regex fallback (heuristic:true) otherwise. Never throws.
4
+ */
5
+ import { readFileSync } from "node:fs";
6
+ import { Parser, Language } from "web-tree-sitter";
7
+ import { EXT_GRAMMAR, resolveWasmFile, resolveRuntimeWasm } from "./grammars.ts";
8
+
9
+ export type SymbolEntry = { name: string; kind: string; line: number };
10
+ export type EdgeEntry = { caller: string; callee: string; line: number };
11
+ export interface ExtractedFile {
12
+ symbols: SymbolEntry[];
13
+ imports: string[];
14
+ edges: EdgeEntry[];
15
+ heuristic: boolean;
16
+ }
17
+
18
+ /** Minimal parser shape — a parserFactory can inject a mock to count calls. */
19
+ export interface ParserLike {
20
+ parse(source: string): { rootNode: any } | null;
21
+ }
22
+
23
+ let parserInitPromise: Promise<void> | null = null;
24
+ const langCache = new Map<string, any>();
25
+
26
+ /** Initialize the web-tree-sitter runtime once. Throws clearly if wasm missing. */
27
+ export async function initParserOnce(): Promise<void> {
28
+ if (!parserInitPromise) {
29
+ const runtime = resolveRuntimeWasm();
30
+ if (!runtime) {
31
+ throw new Error(
32
+ "tree-sitter runtime wasm not found — install tree-sitter-wasms or vendor tree-sitter.wasm next to the executable",
33
+ );
34
+ }
35
+ parserInitPromise = Parser.init({ locateFile: () => resolveRuntimeWasm()! }).then(() => undefined);
36
+ }
37
+ await parserInitPromise;
38
+ }
39
+
40
+ /** Reset init state (tests isolate wasm-missing scenarios). */
41
+ export function resetParserInit(): void {
42
+ parserInitPromise = null;
43
+ langCache.clear();
44
+ }
45
+
46
+ function grammarFor(absPath: string): string | null {
47
+ const i = absPath.lastIndexOf(".");
48
+ if (i < 0) return null;
49
+ return EXT_GRAMMAR[absPath.slice(i + 1).toLowerCase()] ?? null;
50
+ }
51
+
52
+ /**
53
+ * Extract symbols, imports and call edges from one file.
54
+ * Tree-sitter when the grammar wasm resolves and parses; otherwise the regex
55
+ * fallback for ts/tsx/js/jsx/py/go with heuristic:true. Never throws — the
56
+ * worst case is empty + heuristic:true.
57
+ */
58
+ export async function extractFile(
59
+ absPath: string,
60
+ content: string,
61
+ parserFactory?: (grammar: string) => Promise<ParserLike>,
62
+ ): Promise<ExtractedFile> {
63
+ try {
64
+ const grammar = grammarFor(absPath);
65
+ if (grammar) {
66
+ const wasm = resolveWasmFile(grammar);
67
+ if (wasm) {
68
+ try {
69
+ const parser = parserFactory
70
+ ? await parserFactory(grammar)
71
+ : await getParser(wasm);
72
+ const tree = parser.parse(content);
73
+ if (tree?.rootNode) return walkTree(tree.rootNode);
74
+ } catch { /* fall through to regex */ }
75
+ }
76
+ }
77
+ return regexFallback(content, extOf(absPath));
78
+ } catch {
79
+ return { symbols: [], imports: [], edges: [], heuristic: true };
80
+ }
81
+ }
82
+
83
+ /** Force the regex-fallback branch directly (missing wasm / tests). */
84
+ export async function extractFileRegexFallback(content: string, ext: string): Promise<ExtractedFile> {
85
+ return regexFallback(content, ext.startsWith(".") ? ext : "." + ext);
86
+ }
87
+
88
+ async function getParser(wasmPath: string): Promise<ParserLike> {
89
+ await initParserOnce();
90
+ let lang = langCache.get(wasmPath);
91
+ if (!lang) {
92
+ lang = await Language.load(new Uint8Array(readFileSync(wasmPath)));
93
+ langCache.set(wasmPath, lang);
94
+ }
95
+ const parser = new Parser();
96
+ parser.setLanguage(lang);
97
+ return parser as unknown as ParserLike;
98
+ }
99
+
100
+ const DEF_TYPES = new Set([
101
+ "function_declaration", "generator_function_declaration", "function_signature",
102
+ "abstract_class_declaration", "class_declaration", "method_definition",
103
+ "interface_declaration", "type_alias_declaration", "enum_declaration",
104
+ "function_definition", "class_definition", "decorated_definition",
105
+ "method_declaration", "constructor_declaration",
106
+ "struct_type", "union_type", "interface_type", "enum_type", "type_declaration",
107
+ "const_declaration", "var_declaration",
108
+ "function_item", "struct_item", "enum_item", "union_item", "trait_item", "impl_item",
109
+ "type_definition", "struct_specifier", "enum_specifier", "union_specifier",
110
+ "record_declaration", "class",
111
+ ]);
112
+
113
+ const NAME_TOKENS = new Set([
114
+ "type_identifier", "identifier", "field_identifier", "constant",
115
+ "scoped_identifier", "qualified_identifier", "word",
116
+ ]);
117
+
118
+ function nameOf(n: any): string | null {
119
+ const f = n.childForFieldName?.("name");
120
+ if (f?.text) return f.text;
121
+ for (const c of n.children ?? []) {
122
+ if (NAME_TOKENS.has(c.type) && c.text) {
123
+ // skip the "extends X" / type-name collisions in go/rust decl wrappers
124
+ if (c.type === "identifier" && (n.type === "const_declaration" || n.type === "var_declaration")) continue;
125
+ return c.text.split(".").pop() || c.text;
126
+ }
127
+ if (["type_spec", "base_type_specifier", "element_type", "declarator"].includes(c.type)) {
128
+ const inner = nameOf(c);
129
+ if (inner) return inner;
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+
135
+ function calleeOf(n: any): string | null {
136
+ const f = n.childForFieldName?.("function") ?? n.childForFieldName?.("name");
137
+ const text = f?.text ?? null;
138
+ if (!text) return null;
139
+ // strip member paths and generics: obj.method<T>(x) -> method
140
+ const cleaned = text.replace(/<[^<>]*>/g, "").trim();
141
+ const parts = cleaned.split(/[.::]/);
142
+ const last = parts[parts.length - 1]?.trim();
143
+ return last && /^\w+$/.test(last) ? last : null;
144
+ }
145
+
146
+ /** Walk a tree-sitter tree collecting definitions, call edges, import sources. */
147
+ function walkTree(root: any): ExtractedFile {
148
+ const symbols: SymbolEntry[] = [];
149
+ const imports: string[] = [];
150
+ const edges: EdgeEntry[] = [];
151
+
152
+ const lineOf = (n: any): number => (n.startPosition?.row ?? 0) + 1;
153
+
154
+ function walk(n: any, enclosing: string) {
155
+ const t = n.type;
156
+ let next = enclosing;
157
+ if (DEF_TYPES.has(t)) {
158
+ const name = nameOf(n);
159
+ if (name) {
160
+ symbols.push({ name, kind: t, line: lineOf(n) });
161
+ next = name;
162
+ }
163
+ }
164
+ if (t === "call_expression" || t === "call" || t === "invocation_expression") {
165
+ const callee = calleeOf(n);
166
+ if (callee) edges.push({ caller: enclosing || "<module>", callee, line: lineOf(n) });
167
+ }
168
+ if (
169
+ t === "import_statement" || t === "import_declaration" || t === "import_from_statement" ||
170
+ t === "use_declaration" || t === "namespace_use_declaration" || t === "using_directive"
171
+ ) {
172
+ const src = n.childForFieldName?.("source") ?? n.childForFieldName?.("module_name") ?? n.childForFieldName?.("argument");
173
+ if (src?.text) imports.push(stripQuotes(src.text));
174
+ else {
175
+ for (const c of n.children ?? []) {
176
+ if (["dotted_name", "path", "relative_path", "scoped_identifier"].includes(c.type)) {
177
+ imports.push(c.text);
178
+ break;
179
+ }
180
+ if (c.type === "import_spec") {
181
+ const p = c.childForFieldName?.("path");
182
+ if (p?.text) { imports.push(stripQuotes(p.text)); break; }
183
+ }
184
+ if (c.type === "string") { imports.push(stripQuotes(c.text)); break; }
185
+ }
186
+ }
187
+ }
188
+ if (t === "export_statement") {
189
+ const src = n.childForFieldName?.("source");
190
+ if (src?.text) imports.push(stripQuotes(src.text));
191
+ }
192
+ for (const c of n.children ?? []) walk(c, next);
193
+ }
194
+
195
+ walk(root, "");
196
+ return { symbols, imports, edges, heuristic: false };
197
+ }
198
+
199
+ function stripQuotes(s: string): string {
200
+ return s.replace(/^["'`]|["'`]$/g, "");
201
+ }
202
+
203
+ function extOf(absPath: string): string {
204
+ const i = absPath.lastIndexOf(".");
205
+ return i < 0 ? "" : absPath.slice(i).toLowerCase();
206
+ }
207
+
208
+ function lineNum(content: string, index: number): number {
209
+ let n = 1;
210
+ for (let i = 0; i < index && i < content.length; i++) if (content[i] === "\n") n++;
211
+ return n;
212
+ }
213
+
214
+ const KEYWORD_CALLS = new Set(["if", "for", "while", "switch", "catch", "return", "function", "typeof", "await", "new", "do", "else", "match", "case", "range"]);
215
+
216
+ /** Regex fallback for ts/tsx/js/jsx/py/go — always heuristic:true. */
217
+ function regexFallback(content: string, ext: string): ExtractedFile {
218
+ const symbols: SymbolEntry[] = [];
219
+ const imports: string[] = [];
220
+ const edges: EdgeEntry[] = [];
221
+
222
+ if (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx") {
223
+ for (const m of content.matchAll(/(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s*(?:\*)?\s*(\w+)/g))
224
+ symbols.push({ name: m[1], kind: "function", line: lineNum(content, m.index ?? 0) });
225
+ for (const m of content.matchAll(/(?:export\s+(?:default\s+)?)?class\s+(\w+)/g))
226
+ symbols.push({ name: m[1], kind: "class", line: lineNum(content, m.index ?? 0) });
227
+ for (const m of content.matchAll(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=/g))
228
+ symbols.push({ name: m[1], kind: "const", line: lineNum(content, m.index ?? 0) });
229
+ for (const m of content.matchAll(/import\s+(?:[^;]*?\s+from\s+)?["']([^"']+)["']/g))
230
+ imports.push(m[1]);
231
+ for (const m of content.matchAll(/export\s+(?:\{[^}]*\}|\*(?: as \w+)?)\s+from\s+["']([^"']+)["']/g))
232
+ imports.push(m[1]);
233
+ const known = new Set(symbols.map((s) => s.name));
234
+ for (const m of content.matchAll(/(\w+)\s*\(/g)) {
235
+ if (known.has(m[1]) && !KEYWORD_CALLS.has(m[1]))
236
+ edges.push({ caller: "<local>", callee: m[1], line: lineNum(content, m.index ?? 0) });
237
+ }
238
+ } else if (ext === ".py") {
239
+ for (const m of content.matchAll(/^(?:async\s+)?def\s+(\w+)/gm))
240
+ symbols.push({ name: m[1], kind: "function", line: lineNum(content, m.index ?? 0) });
241
+ for (const m of content.matchAll(/^class\s+(\w+)/gm))
242
+ symbols.push({ name: m[1], kind: "class", line: lineNum(content, m.index ?? 0) });
243
+ for (const m of content.matchAll(/^\s*import\s+([\w.]+)/gm)) imports.push(m[1]);
244
+ for (const m of content.matchAll(/^\s*from\s+([\w.]+)/gm)) imports.push(m[1]);
245
+ } else if (ext === ".go") {
246
+ for (const m of content.matchAll(/^func\s+(?:\([^)]*\)\s*)?(\w+)/gm))
247
+ symbols.push({ name: m[1], kind: "function", line: lineNum(content, m.index ?? 0) });
248
+ for (const m of content.matchAll(/^type\s+(\w+)/gm))
249
+ symbols.push({ name: m[1], kind: "type", line: lineNum(content, m.index ?? 0) });
250
+ for (const m of content.matchAll(/import\s+"([^"]+)"/g)) imports.push(m[1]);
251
+ for (const m of content.matchAll(/^\s+[\w.]*\s*"([^"]+)"/gm)) imports.push(m[1]);
252
+ } else if (ext === ".sh" || ext === ".bash" || ext === ".zsh" || ext === ".fish") {
253
+ for (const m of content.matchAll(/^(?:export\s+)?function\s+(\w+)/gm))
254
+ symbols.push({ name: m[1], kind: "function", line: lineNum(content, m.index ?? 0) });
255
+ for (const m of content.matchAll(/^\s*(\w+)\s*=/g))
256
+ symbols.push({ name: m[1], kind: "variable", line: lineNum(content, m.index ?? 0) });
257
+ for (const m of content.matchAll(/^(?:source|\.)\s+["']?([^"'\s]+)/gm)) imports.push(m[1]);
258
+ } else if (ext === ".sql" || ext === ".mysql" || ext === ".psql") {
259
+ for (const m of content.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?PROCEDURE\s+(\w+)/gi))
260
+ symbols.push({ name: m[1], kind: "procedure", line: lineNum(content, m.index ?? 0) });
261
+ for (const m of content.matchAll(/\bCREATE\s+(?:TEMPORARY\s+)?TABLE\s+(\w+)/gi))
262
+ symbols.push({ name: m[1], kind: "table", line: lineNum(content, m.index ?? 0) });
263
+ for (const m of content.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+(\w+)/gi))
264
+ symbols.push({ name: m[1], kind: "function", line: lineNum(content, m.index ?? 0) });
265
+ for (const m of content.matchAll(/^(?:\s*--.*)?\s*(?:FROM|INTO|UPDATE|JOIN|TABLE)\s+(\w+)/gmi))
266
+ imports.push(m[1]);
267
+ } else if (ext === ".hcl" || ext === ".tf") {
268
+ for (const m of content.matchAll(/^\s*(resource|module|variable|output)\s+"(\w+)"/gm))
269
+ symbols.push({ name: m[2], kind: m[1], line: lineNum(content, m.index ?? 0) });
270
+ for (const m of content.matchAll(/^\s*(data|provider)\s+"(\w+)"/gm))
271
+ symbols.push({ name: m[2], kind: m[1], line: lineNum(content, m.index ?? 0) });
272
+ for (const m of content.matchAll(/^\s*source\s+=\s+"([^"]+)"/gm))
273
+ imports.push(m[1]);
274
+ } else if (ext === ".proto" || ext === ".protodevel") {
275
+ for (const m of content.matchAll(/^\s*message\s+(\w+)/gm))
276
+ symbols.push({ name: m[1], kind: "message", line: lineNum(content, m.index ?? 0) });
277
+ for (const m of content.matchAll(/^\s*enum\s+(\w+)/gm))
278
+ symbols.push({ name: m[1], kind: "enum", line: lineNum(content, m.index ?? 0) });
279
+ for (const m of content.matchAll(/^\s*rpc\s+(\w+)/gm))
280
+ symbols.push({ name: m[1], kind: "rpc", line: lineNum(content, m.index ?? 0) });
281
+ for (const m of content.matchAll(/^\s*(?:import|package)\s+"([^"]+)"/gm)) imports.push(m[1]);
282
+ } else if (ext === ".graphql" || ext === ".gql") {
283
+ for (const m of content.matchAll(/^\s*type\s+(\w+)/gm))
284
+ symbols.push({ name: m[1], kind: "type", line: lineNum(content, m.index ?? 0) });
285
+ for (const m of content.matchAll(/^\s*(?:query|mutation|subscription)\s+(\w+)/gm))
286
+ symbols.push({ name: m[1], kind: "operation", line: lineNum(content, m.index ?? 0) });
287
+ for (const m of content.matchAll(/^\s*enum\s+(\w+)/gm))
288
+ symbols.push({ name: m[1], kind: "enum", line: lineNum(content, m.index ?? 0) });
289
+ for (const m of content.matchAll(/^\s*(?:import|extend\s+type)\s+(\w+)/gm)) imports.push(m[1]);
290
+ }
291
+ return { symbols, imports, edges, heuristic: true };
292
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Symbol search and ranking for GoatCode.
3
+ * Provides keyword-based find, hybrid search (keyword + semantic), and ranking.
4
+ */
5
+
6
+ import type { IndexFile, Index } from "./indexer.ts";
7
+ import { semanticSearch } from "./semantic.ts";
8
+ import { VectorIndex } from "./semantic.ts";
9
+ import { getEmbeddingModel } from "./semantic.ts";
10
+
11
+ export interface SearchResult {
12
+ file: string;
13
+ symbols: Array<{ name: string; line: number; score: number; kind: string }>;
14
+ }
15
+
16
+ /** Check if q is a camel-case prefix of name (e.g. "usrInfo" matches "userInfo") */
17
+ function isCamelPrefix(name: string, q: string): boolean {
18
+ // Only match if query has uppercase letters (camel case pattern like "usrInfo")
19
+ if (!/[A-Z]/.test(q)) return false;
20
+ let qi = 0;
21
+ for (let ni = 0; ni < name.length && qi < q.length; ni++) {
22
+ if (name[ni].toLowerCase() === q[qi].toLowerCase()) {
23
+ qi++;
24
+ }
25
+ }
26
+ return qi === q.length;
27
+ }
28
+
29
+ /** Rank symbols by relevance */
30
+ export function rankSymbols(
31
+ symbols: Array<{ name: string; line: number; kind: string }>,
32
+ query: string
33
+ ): Array<{ name: string; line: number; score: number; kind: string }> {
34
+ return symbols
35
+ .map((s) => {
36
+ let score = 0;
37
+ const lowerName = s.name.toLowerCase();
38
+ const lowerQuery = query.toLowerCase();
39
+
40
+ // Exact match
41
+ if (lowerName === lowerQuery) score += 100;
42
+ // Contains match
43
+ if (lowerName.includes(lowerQuery)) score += 50;
44
+ // Prefix match
45
+ if (lowerName.startsWith(lowerQuery)) score += 75;
46
+ // Substring match
47
+ if (lowerName.includes(lowerQuery)) score += 25;
48
+
49
+ // Priority by kind
50
+ if (s.kind.includes("function")) score += 10;
51
+ if (s.kind.includes("class")) score += 8;
52
+ if (s.kind.includes("variable")) score += 5;
53
+
54
+ return { name: s.name, line: s.line, score, kind: s.kind };
55
+ })
56
+ .sort((a, b) => b.score - a.score);
57
+ }
58
+
59
+ /**
60
+ * Find symbols matching query across indexed files.
61
+ * Returns ranked results sorted by relevance score.
62
+ * Includes edge bonuses for graph-connected symbols.
63
+ * All symbols are included in results (non-matching get score 0).
64
+ */
65
+ export function findSymbols(
66
+ index: Index,
67
+ query: string,
68
+ opts: { limit?: number; kind?: string } = {}
69
+ ): Array<{ name: string; file: string; line: number; kind: string; score: number; heuristic?: boolean }> {
70
+ const lowerQuery = query.toLowerCase();
71
+
72
+ // Phase 1: Add ALL symbols to results (non-matching get score 0)
73
+ const results: Array<{ name: string; file: string; line: number; kind: string; score: number; heuristic?: boolean }> = [];
74
+ const resultIndex = new Map<string, number>(); // name -> index in results
75
+
76
+ for (const [file, data] of Object.entries(index.files)) {
77
+ for (const symbol of data.symbols) {
78
+ const lowerName = symbol.name.toLowerCase();
79
+
80
+ // Skip if kind filter doesn't match
81
+ if (opts.kind && !symbol.kind.toLowerCase().includes(opts.kind.toLowerCase())) continue;
82
+
83
+ let score = 0;
84
+ // Exact match
85
+ if (lowerName === lowerQuery) score += 10;
86
+ // Prefix match
87
+ else if (lowerName.startsWith(lowerQuery)) score += 6;
88
+ // CamelCase prefix match (original case preserved)
89
+ else if (isCamelPrefix(symbol.name, query)) score += 6;
90
+ // Contains match
91
+ else if (lowerName.includes(lowerQuery)) score += 3;
92
+
93
+ const idx = results.length;
94
+ results.push({
95
+ name: symbol.name,
96
+ file,
97
+ line: symbol.line,
98
+ kind: symbol.kind,
99
+ score,
100
+ heuristic: data.heuristic,
101
+ });
102
+ resultIndex.set(symbol.name.toLowerCase(), idx);
103
+ }
104
+ }
105
+
106
+ // Phase 2: Add FILE_BONUS for files whose name matches query
107
+ const filePathBonus = new Set<number>();
108
+ for (const [file, data] of Object.entries(index.files)) {
109
+ if (file.toLowerCase().includes(lowerQuery)) {
110
+ for (let i = 0; i < results.length; i++) {
111
+ if (results[i].file === file && !filePathBonus.has(i)) {
112
+ results[i].score += 2;
113
+ filePathBonus.add(i);
114
+ }
115
+ }
116
+ }
117
+ }
118
+
119
+ // Phase 3: Edge bonuses for graph-connected symbols
120
+ // Only direct partners of symbols with score >= 3 get +2 bonus
121
+ for (const edge of index.edges) {
122
+ const callerIdx = resultIndex.get(edge.caller.toLowerCase());
123
+ const calleeIdx = resultIndex.get(edge.callee.toLowerCase());
124
+
125
+ if (callerIdx !== undefined && calleeIdx !== undefined) {
126
+ // If caller matches query well, give callee a small edge bonus
127
+ if (results[callerIdx].score >= 3) {
128
+ results[calleeIdx].score += 2;
129
+ }
130
+ // If callee matches query well, give caller a small edge bonus
131
+ if (results[calleeIdx].score >= 3) {
132
+ results[callerIdx].score += 2;
133
+ }
134
+ }
135
+ }
136
+
137
+ return results.sort((a, b) => b.score - a.score).slice(0, opts.limit ?? 20);
138
+ }
139
+
140
+ /**
141
+ * Semantic search wrapper — builds vector index from files if missing,
142
+ * then returns top-k semantically relevant files with their symbols.
143
+ */
144
+ export async function semanticFind(
145
+ index: Index,
146
+ query: string,
147
+ opts: { limit?: number } = {}
148
+ ): Promise<Array<{ file: string; score: number; symbols: Array<{ name: string; line: number; score: number }> }>> {
149
+ // Ensure vectorIndex exists
150
+ if (!index.vectorIndex) {
151
+ index.vectorIndex = new VectorIndex();
152
+ await buildVectorIndex(index);
153
+ }
154
+
155
+ return semanticSearch(query, index.vectorIndex, opts.limit ?? 10);
156
+ }
157
+
158
+ /** Build semantic vectors for all indexed files */
159
+ export async function buildVectorIndex(index: Index): Promise<void> {
160
+ const model = getEmbeddingModel();
161
+ const vi = new VectorIndex();
162
+
163
+ for (const [file, data] of Object.entries(index.files)) {
164
+ // Use first 200 chars of file content as embedding source
165
+ const content = `${data.repo}/${file} ${data.symbols.map((s) => s.name).join(" ")}`;
166
+ const vector = await model.embed(content.slice(0, 500));
167
+ vi.add(file, vector, { repo: data.repo });
168
+ }
169
+
170
+ index.vectorIndex = vi;
171
+ }
172
+
173
+ /** Hybrid search: keyword + semantic fusion using Reciprocal Rank Fusion */
174
+ export async function hybridSearch(
175
+ query: string,
176
+ index: Index,
177
+ topK: number = 20
178
+ ): Promise<SearchResult[]> {
179
+ // Keyword search
180
+ const keywordResults: SearchResult[] = [];
181
+ const kwSymbols = findSymbols(index, query, { limit: 50 });
182
+ const fileMap = new Map<string, Array<{ name: string; line: number; score: number; kind: string }>>();
183
+ for (const r of kwSymbols) {
184
+ if (!fileMap.has(r.file)) fileMap.set(r.file, []);
185
+ fileMap.get(r.file)!.push({ name: r.name, line: r.line, score: r.score, kind: r.kind });
186
+ }
187
+ let kwRank = 0;
188
+ for (const file of fileMap.keys()) {
189
+ kwRank++;
190
+ keywordResults.push({
191
+ file,
192
+ symbols: fileMap.get(file)!,
193
+ });
194
+ }
195
+
196
+ // Semantic search
197
+ let semanticResults: Array<{ file: string; score: number }> = [];
198
+ try {
199
+ const model = getEmbeddingModel();
200
+ await model.initialize();
201
+ if (!index.vectorIndex) {
202
+ index.vectorIndex = new VectorIndex();
203
+ await buildVectorIndex(index);
204
+ }
205
+ const queryVector = await model.embed(query.slice(0, 500));
206
+ semanticResults = index.vectorIndex.search(queryVector, 10);
207
+ } catch {
208
+ // Semantic unavailable — return keyword-only results
209
+ }
210
+
211
+ // Combine with Reciprocal Rank Fusion (k=60)
212
+ const fused: Map<string, { score: number; symbols: Array<{ name: string; line: number; score: number; kind: string }> }> = new Map();
213
+
214
+ // Keyword scores
215
+ for (let i = 0; i < keywordResults.length; i++) {
216
+ const result = keywordResults[i];
217
+ const rank = i + 1;
218
+ const keyScore = 1 / (60 + rank);
219
+ if (!fused.has(result.file)) fused.set(result.file, { score: 0, symbols: [] });
220
+ fused.get(result.file)!.score += keyScore;
221
+ fused.get(result.file)!.symbols.push(...result.symbols);
222
+ }
223
+
224
+ // Semantic scores
225
+ for (let i = 0; i < semanticResults.length; i++) {
226
+ const r = semanticResults[i];
227
+ const rank = i + 1;
228
+ const semScore = r.score / (60 + rank);
229
+ if (!fused.has(r.file)) fused.set(r.file, { score: 0, symbols: [] });
230
+ fused.get(r.file)!.score += semScore;
231
+ // Append semantic-only file entries
232
+ if (fused.get(r.file)!.symbols.length === 0) {
233
+ fused.get(r.file)!.symbols.push({ name: r.file, line: 0, score: r.score, kind: "file" });
234
+ }
235
+ }
236
+
237
+ // Sort by fused score, take topK
238
+ const final = [...fused.entries()]
239
+ .sort((a, b) => b[1].score - a[1].score)
240
+ .slice(0, topK)
241
+ .map(([file, data]) => ({ file, symbols: data.symbols }));
242
+
243
+ return final;
244
+ }