Skip to content

Commit d137e96

Browse files
Agents can search the code by what it does: a new code_search tool ranks chunks of the project and returns file, line range and the matching lines.
It works for every engine, not just the local one. It builds .nexus/index.json on first use, and if a matched file changed since then it rebuilds before answering, so line numbers are never stale. The /index command now shares the same indexer.
1 parent 9a46f1b commit d137e96

5 files changed

Lines changed: 126 additions & 11 deletions

File tree

‎darknode.js‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1429,7 +1429,7 @@ const CODER_SCHEMA = { type: "object", properties: { thought: { type: "string" }
14291429
// it has no tools. normalizeToolCall recovers the real name + args so tools still fire.
14301430
const TOOL_ARGKEY = { run_command: "command", run_background: "command", read_file: "path", write_file: "path", edit_file: "path", multi_edit: "path", multiedit: "path", apply_patch: "patch", patch: "patch", list_dir: "path", make_dir: "path", mkdir: "path", delete: "path", delete_file: "path", rm: "path", move: "from", copy: "from", search: "pattern", grep: "pattern", find: "glob", glob: "glob", http_fetch: "url", web_fetch: "url", fetch_url: "url", http: "url", web_search: "query", discover: "query", remember: "text", check_background: "id", stop_background: "id", list_processes: "filter", batch: "ops", batch_read: "ops", browser_read: "target", browser_page: "target", browser_eval: "expression", browser_exec: "expression", browser_screenshot: "path", browser_shot: "path", ask_user: "question", ask_question: "question", ask: "question" };
14311431
const KNOWN_ARGKEYS = new Set(["path", "command", "content", "query", "q", "url", "pattern", "glob", "find", "text", "note", "id", "filter", "to", "from", "dest", "name", "tasks", "todos", "items", "method", "replace", "recursive"]);
1432-
const KNOWN_TOOLS = new Set(["read_file", "write_file", "edit_file", "list_dir", "run_command", "run_background", "check_background", "stop_background", "search", "grep", "find", "find_files", "glob", "http_fetch", "web_fetch", "fetch_url", "http", "web_search", "search_web", "google", "todo_write", "todos", "todo_list", "write_todos", "sysinfo", "system_info", "list_processes", "ps", "make_dir", "mkdir", "move", "rename", "move_file", "copy", "copy_file", "delete", "delete_file", "rm", "remember", "discover", "spawn_agents", "repo_map", "repomap", "multi_edit", "multiedit", "apply_patch", "patch", "verify", "run_tests", "test_project", "find_symbol", "symbol", "goto", "find_references", "references", "find_refs", "usages", "callers", "module_graph", "import_graph", "deps_graph", "dependents", "importers", "outline", "file_outline", "symbols", "read_symbol", "read_function", "show_symbol", "json_query", "jq", "read_json", "undo_edit", "replace_in_files", "wait_for", "write_stdin", "batch", "batch_read", "invariants", "check_invariants", "difflint", "attest", "attestation", "capability_attest", "bisect", "regression_bisect", "explain_break", "explainbreak", "blame_turn", "shrink", "minimize_change", "ddmin", "browser_status", "browser_tabs", "browser_list", "browser_read", "browser_page", "browser_eval", "browser_exec", "browser_screenshot", "browser_shot", "ask_user", "ask_question", "ask"]);
1432+
const KNOWN_TOOLS = new Set(["code_search", "read_file", "write_file", "edit_file", "list_dir", "run_command", "run_background", "check_background", "stop_background", "search", "grep", "find", "find_files", "glob", "http_fetch", "web_fetch", "fetch_url", "http", "web_search", "search_web", "google", "todo_write", "todos", "todo_list", "write_todos", "sysinfo", "system_info", "list_processes", "ps", "make_dir", "mkdir", "move", "rename", "move_file", "copy", "copy_file", "delete", "delete_file", "rm", "remember", "discover", "spawn_agents", "repo_map", "repomap", "multi_edit", "multiedit", "apply_patch", "patch", "verify", "run_tests", "test_project", "find_symbol", "symbol", "goto", "find_references", "references", "find_refs", "usages", "callers", "module_graph", "import_graph", "deps_graph", "dependents", "importers", "outline", "file_outline", "symbols", "read_symbol", "read_function", "show_symbol", "json_query", "jq", "read_json", "undo_edit", "replace_in_files", "wait_for", "write_stdin", "batch", "batch_read", "invariants", "check_invariants", "difflint", "attest", "attestation", "capability_attest", "bisect", "regression_bisect", "explain_break", "explainbreak", "blame_turn", "shrink", "minimize_change", "ddmin", "browser_status", "browser_tabs", "browser_list", "browser_read", "browser_page", "browser_eval", "browser_exec", "browser_screenshot", "browser_shot", "ask_user", "ask_question", "ask"]);
14331433
// A tool "name" that is really a shell command line — weak models often emit
14341434
// {tool:"cat /etc/passwd"} or {tool:"ls /bin/*"} instead of run_command.
14351435
const SHELL_CMD = /^(sudo\s+)?(ls|cat|grep|egrep|fgrep|echo|cd|pwd|whoami|id|uname|hostname|ps|top|df|du|free|date|env|printenv|which|type|find|locate|head|tail|awk|sed|cut|tr|sort|uniq|wc|xargs|tee|curl|wget|ping|traceroute|nmap|nc|ncat|dig|host|nslookup|ip|ifconfig|iwconfig|netstat|ss|arp|route|cp|mv|rm|mkdir|rmdir|touch|ln|stat|file|chmod|chown|tar|gzip|gunzip|zip|unzip|git|make|gcc|python3?|node|npm|npx|pip3?|bash|sh|zsh|kill|pkill|killall|systemctl|service|apt|apt-get|dpkg|ssh|scp|rsync|darknode|sentinel|nexus|nikto|sqlmap|hydra|john|hashcat|gobuster|ffuf|masscan|whatweb|searchsploit|msfconsole)(\s|$)/i;
@@ -2407,6 +2407,7 @@ async function deviceTool(name, a, cwd) {
24072407
// outline: the structural symbol outline of ONE file (functions/classes/types in source order with
24082408
// line numbers) — jump around a big unfamiliar file fast. Reuses the repo-map symbol extractor.
24092409
if (name === "read_symbol" || name === "read_function" || name === "show_symbol") return require("./lib/nexus/read-symbol").readSymbolTool(a, cwd, rp);
2410+
if (name === "code_search" || name === "semantic_search" || name === "search_code") return require("./lib/nexus/code-search").codeSearchTool(a, cwd);
24102411
if (name === "json_query" || name === "jq" || name === "read_json") return require("./lib/nexus/json-query").jsonQueryTool(a, cwd, rp);
24112412
if (name === "outline" || name === "file_outline" || name === "symbols") {
24122413
if (!(a.path || a.file)) return { error: "outline needs path (one file) — for the whole project use repo_map" };
@@ -3034,14 +3035,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) {
30343035
// .nexus/index.json: a BM25 index over ~60-line chunks (lib/nexus/bm25.js). An index from an
30353036
// older Nexus (a per-file keyword list) is ignored until /index is run again.
30363037
let index = null; try { const raw = JSON.parse(stripBom(fs.readFileSync(path.join(cwd, ".nexus", "index.json"), "utf8"))); if (raw && raw.version === bm25.VERSION && raw.docs) index = raw; } catch (_) {}
3037-
const buildIndex = () => {
3038-
const files = {}; const SKIP = /(^|\/)(\.git|node_modules|\.nexus|dist|build|\.cache|\.next|target|__pycache__)(\/|$)/;
3039-
const CODE = /\.(js|jsx|ts|tsx|py|rb|go|rs|java|c|h|cpp|cc|cs|php|swift|kt|sh|css|scss|html|json|md|yml|yaml|toml)$/i;
3040-
const GEN = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|Cargo\.lock)$|\.(min\.js|min\.css|map)$/;
3041-
const list = []; let bytes = 0;
3042-
const walk = (d) => { let ents; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { return; } for (const e of ents) { const fp = path.join(d, e.name); if (SKIP.test(e.name)) continue; if (e.isDirectory()) walk(fp); else if (CODE.test(e.name) && !GEN.test(e.name)) { try { if (fs.statSync(fp).size > 2000000 || bytes > 64 * 1024 * 1024) continue; const txt = fs.readFileSync(fp, "utf8"); bytes += txt.length; list.push({ path: path.relative(cwd, fp), content: txt }); } catch (_) {} } if (list.length > 4000) return; } };
3043-
walk(cwd); index = Object.assign(bm25.buildIndex(list), { files: list.length, ts: Date.now() }); try { fs.mkdirSync(path.join(cwd, ".nexus"), { recursive: true }); fs.writeFileSync(path.join(cwd, ".nexus", "index.json"), JSON.stringify(index)); } catch (_) {} return list.length;
3044-
};
3038+
const buildIndex = () => { index = require("./lib/nexus/code-search").buildAndSave(cwd); return index.files; };
30453039
// the chunks most relevant to the prompt by BM25, skipping files already pinned or @-mentioned
30463040
// (they are in the prompt anyway): [{ path, start, end, score }]
30473041
const retrieve = (text, k) => { if (!index) return []; return bm25.search(index, text, { k: (k || 3) + 4 }).filter((h) => !pinned.has(h.path) && !text.includes("@" + h.path)).slice(0, k || 3); };
@@ -4383,7 +4377,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) {
43834377
else if (imgAttach.length) oMsgs.push({ role: "user", content: promptText, images: imgAttach.map((im) => im.b64) }); // Ollama vision (llava / llama3.2-vision / …)
43844378
else oMsgs.push({ role: "user", content: promptText });
43854379
sess.inTok += Math.ceil(promptText.length / 4);
4386-
const olbl = (n, a) => n === "read_symbol" ? "ReadSymbol(" + relP(a.path) + " " + oneline(a.name || "", 30) + ")" : n === "json_query" ? "JsonQuery(" + relP(a.path) + (a.query ? " " + oneline(a.query, 30) : "") + ")" : n === "undo_edit" ? "UndoEdit(" + relP(a.path) + ")"
4380+
const olbl = (n, a) => n === "code_search" ? "CodeSearch(" + oneline(a.query || "", 40) + ")" : n === "read_symbol" ? "ReadSymbol(" + relP(a.path) + " " + oneline(a.name || "", 30) + ")" : n === "json_query" ? "JsonQuery(" + relP(a.path) + (a.query ? " " + oneline(a.query, 30) : "") + ")" : n === "undo_edit" ? "UndoEdit(" + relP(a.path) + ")"
43874381
: n === "replace_in_files" ? (a.dry_run || a.preview ? "ReplacePreview(" : "Replace(") + oneline(String(a.find != null ? a.find : a.pattern || ""), 24) + " → " + oneline(String(a.replace != null ? a.replace : a.replacement || ""), 24) + ")" : n === "wait_for" ? "WaitFor(" + oneline(String(a.port ? "port " + a.port : a.url || a.file || ((a.job || a.id || "") + (a.pattern ? " /" + a.pattern + "/" : ""))), 40) + ")"
43884382
: n === "write_stdin" ? "Stdin(" + (a.id || a.job || "?") + ": " + oneline(String(a.input != null ? a.input : a.text || ""), 30) + ")" : n === "read_file" ? "Read(" + relP(a.path) + ")" : n === "write_file" ? "Write(" + relP(a.path) + ")" : n === "edit_file" ? "Update(" + relP(a.path) + ")" : (n === "multi_edit" || n === "multiedit") ? "Update(" + relP(a.path) + ")" : (n === "apply_patch" || n === "patch") ? "Patch(" + ((_pf) => _pf.length === 1 && _pf[0].file ? relP(_pf[0].file) : (_pf.length || "?") + " files")(parsePatch(a.patch || a.diff || a.content || a.input || "") || []) + ")" : n === "run_command" ? "Bash(" + oneline(a.command, Math.max(40, cols() - 30)) + ")" : n === "run_background" ? "Background(" + oneline(a.command, 32) + ")" : n === "check_background" ? "CheckJob(" + (a.id || "all") + ")" : n === "stop_background" ? "StopJob(" + (a.id || "?") + ")" : n === "list_dir" ? "List(" + (a.path || ".") + ")" : (n === "search" || n === "grep") ? "Search(" + oneline(a.pattern || a.query, 30) + ")" : (n === "find" || n === "find_files" || n === "glob") ? "Find(" + oneline(a.glob || a.pattern || a.name, 30) + ")" : (n === "http_fetch" || n === "web_fetch" || n === "fetch_url" || n === "http") ? "Fetch(" + oneline(a.url, 36) + ")" : (n === "web_search" || n === "search_web" || n === "google") ? "WebSearch(" + oneline(a.query || a.q, 30) + ")" : (n === "view_image" || n === "view_img" || n === "show_image") ? "ViewImage(" + base(a.path || a.file || a.image || "") + ")" : (n === "todo_write" || n === "todos" || n === "todo_list" || n === "write_todos") ? "Update Todos" : (n === "sysinfo" || n === "system_info") ? "Sysinfo()" : (n === "list_processes" || n === "ps") ? "Processes()" : (n === "make_dir" || n === "mkdir") ? "Mkdir(" + base(a.path) + ")" : (n === "move" || n === "rename" || n === "move_file") ? "Move(" + base(a.to || a.dest) + ")" : (n === "copy" || n === "copy_file") ? "Copy(" + base(a.to || a.dest) + ")" : (n === "delete" || n === "delete_file" || n === "rm") ? "Delete(" + base(a.path) + ")" : n === "spawn_agents" ? "Task(" + ((a.tasks || []).length) + " agents)" : (n === "repo_map" || n === "repomap" || n === "map") ? "RepoMap()" : (n === "find_symbol" || n === "symbol" || n === "goto") ? "Symbol(" + oneline(a.name || a.symbol || a.query || "", 26) + ")" : (n === "find_references" || n === "references" || n === "find_refs" || n === "usages" || n === "callers") ? "References(" + oneline(a.name || a.symbol || a.query || "", 24) + ")" : (n === "module_graph" || n === "import_graph" || n === "deps_graph" || n === "dependents" || n === "importers") ? "ModuleGraph(" + (a.path || a.file || a.target ? base(a.path || a.file || a.target) : "project") + ")" : (n === "outline" || n === "file_outline" || n === "symbols") ? "Outline(" + base(a.path || a.file || "") + ")" : (n === "verify" || n === "run_tests" || n === "test_project") ? "Verify(" + oneline(a.kind || a.command || "auto", 24) + ")" : (n === "ask_user" || n === "ask_question" || n === "ask") ? "AskUser(" + oneline(a.question || a.prompt || a.q || "", 28) + ")" : n === "remember" ? "Remember(" + oneline(a.text || a.note || "", 34) + ")" : n === "discover" ? "Discover(" + oneline(a.query || a.q || "", 30) + ")" : (n === "batch" || n === "batch_read") ? "Batch(" + ((a.ops || a.operations || a.calls || []).length) + " ops)" : (n === "invariants" || n === "check_invariants" || n === "difflint") ? "Invariants()" : (n === "attest" || n === "attestation" || n === "capability_attest") ? "Attest()" : (n === "bisect" || n === "regression_bisect") ? "Bisect(" + oneline(a.test || a.command || "auto", 24) + ")" : (n === "explain_break" || n === "explainbreak" || n === "blame_turn") ? "ExplainBreak()" : (n === "shrink" || n === "minimize_change" || n === "ddmin") ? "Shrink(" + oneline(a.test || a.command || "auto", 24) + ")" : String(n).startsWith("mcp__") ? String(n).replace(/^mcp__/, "").replace("__", ":") + "()" : n + "()";
43894383
(async () => {

‎lib/nexus/code-search.js‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
"use strict";
2+
// code_search — find the part of the codebase a question is about ("where do we retry failed
3+
// uploads") when the exact string to grep for is unknown. Ranks ~60-line chunks with BM25
4+
// (lib/nexus/bm25.js) over the index the TUI's /index command keeps in .nexus/index.json, building
5+
// it on first use. Each hit comes back as path:start-end plus the lines inside it that mention the
6+
// query's words, read fresh from disk, so the agent reads or edits exactly that range next.
7+
// A hit file changed since the index was built triggers one rebuild, so ranges never go stale.
8+
9+
const fs = require("fs");
10+
const path = require("path");
11+
const bm25 = require("./bm25");
12+
13+
const SKIP = /(^|\/)(\.git|node_modules|\.nexus|dist|build|\.cache|\.next|target|__pycache__)(\/|$)/;
14+
const CODE = /\.(js|jsx|ts|tsx|mjs|cjs|py|rb|go|rs|java|c|h|cpp|cc|cs|php|swift|kt|sh|css|scss|html|json|md|yml|yaml|toml)$/i;
15+
const GEN = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|Cargo\.lock)$|\.(min\.js|min\.css|map)$/;
16+
const MAX_FILE = 2000000, MAX_BYTES = 64 * 1024 * 1024, MAX_FILES = 4000;
17+
18+
const indexPath = (cwd) => path.join(cwd, ".nexus", "index.json");
19+
20+
// Source files under cwd as [{ path, content }] (relative paths), skipping vendored, built and
21+
// generated files; capped so a huge tree can't stall the agent.
22+
function collectFiles(cwd) {
23+
const list = []; let bytes = 0;
24+
const walk = (d) => {
25+
let ents; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { return; }
26+
for (const e of ents) {
27+
if (list.length >= MAX_FILES) return;
28+
if (SKIP.test(e.name)) continue;
29+
const fp = path.join(d, e.name);
30+
if (e.isDirectory()) walk(fp);
31+
else if (e.isFile() && CODE.test(e.name) && !GEN.test(e.name)) {
32+
try { if (fs.statSync(fp).size > MAX_FILE || bytes > MAX_BYTES) continue; const txt = fs.readFileSync(fp, "utf8"); bytes += txt.length; list.push({ path: path.relative(cwd, fp).split(path.sep).join("/"), content: txt }); } catch (_) {}
33+
}
34+
}
35+
};
36+
walk(cwd);
37+
return list;
38+
}
39+
40+
// The stored index if it is from this BM25 version, else null.
41+
function loadIndex(cwd) {
42+
try { const raw = JSON.parse(fs.readFileSync(indexPath(cwd), "utf8").replace(/^/, "")); if (raw && raw.version === bm25.VERSION && raw.docs) return raw; } catch (_) {}
43+
return null;
44+
}
45+
46+
// Index cwd and store it in .nexus/index.json (best effort: a read-only tree still gets an index in memory).
47+
function buildAndSave(cwd) {
48+
const list = collectFiles(cwd);
49+
const index = Object.assign(bm25.buildIndex(list), { files: list.length, ts: Date.now() });
50+
try { fs.mkdirSync(path.join(cwd, ".nexus"), { recursive: true }); fs.writeFileSync(indexPath(cwd), JSON.stringify(index)); } catch (_) {}
51+
return index;
52+
}
53+
54+
// Lines inside [start, end] that contain a query word, numbered, at most `max`.
55+
function matchingLines(text, start, end, terms, max) {
56+
const lines = String(text).split("\n").slice(start - 1, end);
57+
const out = [];
58+
for (let i = 0; i < lines.length && out.length < max; i++) {
59+
const toks = bm25.tokenize(lines[i]);
60+
if (toks.some((t) => terms.has(t))) out.push((start + i) + ": " + lines[i].trim().slice(0, 160));
61+
}
62+
return out;
63+
}
64+
65+
// a: { query, k?, path? }. Never throws; returns { error } on bad input.
66+
function codeSearchTool(a, cwd, deps) {
67+
a = a || {};
68+
const query = String(a.query || a.q || a.question || "").trim();
69+
if (!query) return { error: "code_search needs {query} — describe what the code does, e.g. {query:\"where failed uploads are retried\"}" };
70+
const k = Math.max(1, Math.min(20, Number(a.k || a.limit) || 6));
71+
const under = a.path ? String(a.path).replace(/^\.\//, "").replace(/\/+$/, "") : "";
72+
const root = path.resolve(cwd);
73+
let index = loadIndex(cwd), built = false;
74+
if (!index) { index = buildAndSave(cwd); built = true; }
75+
const run = () => bm25.search(index, query, { k: under ? k + 30 : k }).filter((h) => !under || h.path === under || h.path.startsWith(under + "/")).slice(0, k);
76+
let hits = run();
77+
// a hit file edited (or deleted) after the index was built: its line ranges may be off, rebuild once
78+
if (!built && hits.some((h) => { try { return fs.statSync(path.join(root, h.path)).mtimeMs > (index.ts || 0); } catch (_) { return true; } })) {
79+
index = buildAndSave(cwd); built = true; hits = run();
80+
}
81+
const terms = new Set(bm25.tokenize(query));
82+
const results = [];
83+
for (const h of hits) {
84+
const fp = path.resolve(root, h.path);
85+
if (fp !== root && !fp.startsWith(root + path.sep)) continue; // an index entry pointing outside the project
86+
let text = ""; try { text = fs.readFileSync(fp, "utf8"); } catch (_) { continue; }
87+
results.push({ path: h.path, lines: h.start + "-" + h.end, score: Math.round(h.score * 100) / 100, matches: matchingLines(text, h.start, h.end, terms, 6) });
88+
}
89+
const out = { query, results, indexed_files: index.files || 0 };
90+
if (built) out.note = "index built now (" + (index.files || 0) + " files); later searches reuse .nexus/index.json";
91+
if (!results.length) out.hint = "no chunk matched those words — try other words for the same idea, or grep for an exact string";
92+
return out;
93+
}
94+
95+
module.exports = { codeSearchTool, collectFiles, loadIndex, buildAndSave, matchingLines };

‎lib/nexus/costsave.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ function collapseToolOutput(result) {
200200
// answer is byte-identical to one already in its context. Send a pointer
201201
// instead of the duplicate. The earlier copy is checked to still be in history
202202
// unchanged (not stubbed or trimmed), so the pointer always resolves.
203-
const READ_ONLY = new Set(["search", "grep", "find", "find_files", "glob", "list_dir", "list", "ls", "repo_map", "outline", "file_outline", "symbols", "find_symbol", "find_references", "references", "module_graph", "import_graph", "json_query", "read_symbol"]);
203+
const READ_ONLY = new Set(["search", "grep", "find", "find_files", "glob", "list_dir", "list", "ls", "repo_map", "outline", "file_outline", "symbols", "find_symbol", "find_references", "references", "module_graph", "import_graph", "json_query", "read_symbol", "code_search"]);
204204
function createToolMemo() {
205205
const seen = new Map();
206206
return {

0 commit comments

Comments
 (0)