AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
research: AST + graph + FTS for AI vulnerability finding at scale
Xerj Squad A1b575acb22ce
diff --git a/docs/examples/ast-vuln-graph/README.md b/docs/examples/ast-vuln-graph/README.mdnew file mode 100644index 000000000..a6db5e6b6--- /dev/null+++ b/docs/examples/ast-vuln-graph/README.md@@ -0,0 +1,28 @@+# AST + graph vulnerability finding (prototype)++Finds interprocedural vulnerabilities in PHP/WordPress that per-file tools miss,+and hands an AI only the code on each taint path — far fewer tokens. Full+write-up: [`docs/research/ast-graph-vuln-detection.md`](../../research/ast-graph-vuln-detection.md).++## Run it++```bash+pip install phply+python3 make_demo_plugin.py ./acme-plugin # 6 planted vulns among ~60 benign files+python3 extract_ast.py ./acme-plugin # AST -> taint graph -> findings+```++Expected: **6/6** vulnerabilities, including the interprocedural SQLi+(`acme_ajax_search -> acme_find_items`, unauthenticated), the interprocedural+XSS, and the missing-nonce CSRF — none of which a single-file scan produces.+`ast_facts.json` holds the per-function facts (index these into XERJ for the+FTS/semantic navigation layer described in the research doc).++## What each file does++- `make_demo_plugin.py` — reproducible vulnerable WordPress plugin (ground truth).+- `extract_ast.py` — parses PHP with phply, builds per-function taint facts and+ the call graph, and reports interprocedural source→sink findings + CSRF.++This is triage: it surfaces real, reachable patterns so an AI can confirm+exploitability with minimal context. See the research doc for the honest limits.diff --git a/docs/examples/ast-vuln-graph/extract_ast.py b/docs/examples/ast-vuln-graph/extract_ast.pynew file mode 100644index 000000000..e231fffbe--- /dev/null+++ b/docs/examples/ast-vuln-graph/extract_ast.py@@ -0,0 +1,134 @@+#!/usr/bin/env python3+"""AST -> taint graph for PHP/WordPress. Emits one 'function fact' per function+(for XERJ) and the interprocedural source->sink findings a per-file scan misses.+"""+import glob, json, os, sys+from phply import phplex, phpast as ast+from phply.phpparse import make_parser++SRC = {"$_GET","$_POST","$_REQUEST","$_COOKIE","$_SERVER","$_FILES"}+SQL = {"query","get_results","get_var","get_row","get_col"}+DANGER= {"unserialize","eval","exec","system","shell_exec","passthru","assert","include","require"}+STATE = {"update_option","delete_option","add_option","wp_insert_post",+ "wp_update_post","wp_delete_post","update_user_meta","add_user_meta"}+SANIT = {"esc_html","esc_attr","esc_url","sanitize_text_field","sanitize_key","absint",+ "intval","wp_verify_nonce","check_admin_referer","wp_kses","prepare"}++def walk(n):+ if isinstance(n, ast.Node):+ yield n+ for f in n.fields:+ yield from walk(getattr(n, f))+ elif isinstance(n, (list, tuple)):+ for x in n: yield from walk(x)++def analyse_body(nodes):+ src, sinks, san, calls = set(), [], set(), set()+ for n in nodes:+ for m in walk(n):+ t = type(m).__name__+ if t == "Variable" and m.name in SRC: src.add(m.name)+ elif t == "MethodCall" and m.name in SQL: sinks.append(("sql", m.name))+ elif t == "Echo": sinks.append(("xss", "echo"))+ elif t == "Print": sinks.append(("xss", "print"))+ elif t == "Include": sinks.append(("lfi", "include"))+ elif t == "FunctionCall":+ if m.name in DANGER: sinks.append((m.name, m.name))+ if m.name in STATE: sinks.append(("state", m.name))+ if m.name in SANIT: san.add(m.name)+ calls.add(m.name) # candidate call edge (user fn resolved later)+ elif t == "MethodCall" and m.name in SANIT: san.add(m.name)+ return src, sinks, san, calls++def main(root):+ parser = make_parser()+ funcs = {} # name -> fact+ hooks = {} # function_name -> {'entry':True,'nopriv':bool}+ for path in glob.glob(f"{root}/**/*.php", recursive=True):+ try:+ tree = parser.parse(open(path, encoding="utf-8", errors="replace").read(),+ lexer=phplex.lexer.clone())+ except Exception:+ continue+ rel = os.path.relpath(path, root)+ for n in walk(tree):+ t = type(n).__name__+ if t == "Function":+ src, sinks, san, calls = analyse_body(n.nodes)+ funcs[n.name] = {+ "file": rel, "func": n.name, "line": n.lineno,+ "sources": sorted(src),+ "sinks": sorted({s[0] for s in sinks}),+ "sink_calls": sorted({s[1] for s in sinks}),+ "sanitizers": sorted(san),+ "calls": sorted(calls),+ "params": [p.name for p in n.params],+ }+ elif t == "FunctionCall" and n.name in ("add_action","add_filter"):+ # add_action('hook','callback')+ args=[p.node for p in n.params if isinstance(p, ast.Parameter)]+ if len(args)>=2 and isinstance(args[0],str) and isinstance(args[1],str):+ hooks[args[1]] = {"entry": True,+ "nopriv": "nopriv" in args[0],+ "admin": args[0].startswith(("admin_post","wp_ajax"))}+ # resolve call edges to user functions only+ for f in funcs.values():+ f["calls"] = [c for c in f["calls"] if c in funcs]+ f["entry"] = bool(hooks.get(f["func"], {}).get("entry"))+ f["nopriv"] = bool(hooks.get(f["func"], {}).get("nopriv"))++ # ── interprocedural taint: source -> (calls*) -> sink, no sanitizer on path ──+ findings = []+ def dfs(start):+ stack=[(start,[start],set(funcs[start]["sanitizers"]))]+ seen=set()+ while stack:+ cur,path,san=stack.pop()+ if cur in seen: continue+ seen.add(cur)+ f=funcs[cur]+ if f["sinks"] and not san:+ findings.append({"sink_type":f["sinks"], "sink_func":cur,+ "sink_file":f["file"], "path":path,+ "source_func":path[0],+ "unauth": funcs[path[0]].get("nopriv", False)})+ for cal in f["calls"]:+ stack.append((cal, path+[cal], san|set(funcs[cal]["sanitizers"])))+ for name,f in funcs.items():+ if f["sources"]: # a taint source starts a path+ dfs(name)+ # ── CSRF: entry handler performs a state change with no nonce check ──+ def reachable(start):+ seen=set(); stack=[start]+ while stack:+ c=stack.pop()+ if c in seen or c not in funcs: continue+ seen.add(c); stack+=funcs[c]["calls"]+ return seen+ for name,f in funcs.items():+ if not f.get("entry"): continue+ sub=reachable(name)+ does_state = any("state" in funcs[c]["sinks"] for c in sub)+ has_nonce = any(("wp_verify_nonce" in funcs[c]["sanitizers"]+ or "check_admin_referer" in funcs[c]["sanitizers"]) for c in sub)+ if does_state and not has_nonce:+ findings.append({"sink_type":["csrf"], "sink_func":name, "sink_file":f["file"],+ "path":[name], "source_func":name, "unauth":f.get("nopriv",False)})+ # dedupe findings by (source,sink)+ uniq={}+ for x in findings:+ uniq[(x["source_func"],x["sink_func"],tuple(x["sink_type"]))]=x+ findings=list(uniq.values())++ json.dump({"functions":list(funcs.values()),"findings":findings},+ open("ast_facts.json","w"), indent=2)+ print(f"parsed {len(funcs)} functions; {len(findings)} taint findings")+ return funcs, findings++if __name__=="__main__":+ funcs,findings=main(sys.argv[1] if len(sys.argv)>1 else "acme-plugin")+ print("\nINTERPROCEDURAL TAINT FINDINGS (AST graph, no LLM):")+ for x in findings:+ chain=" -> ".join(x["path"])+ tag=" [UNAUTH]" if x["unauth"] else ""+ print(f" {'/'.join(x['sink_type'])}: {chain} (sink in {x['sink_file']}){tag}")diff --git a/docs/examples/ast-vuln-graph/make_demo_plugin.py b/docs/examples/ast-vuln-graph/make_demo_plugin.pynew file mode 100644index 000000000..469886bbd--- /dev/null+++ b/docs/examples/ast-vuln-graph/make_demo_plugin.py@@ -0,0 +1,67 @@+#!/usr/bin/env python3+"""Reproducible vulnerable WordPress plugin for the AST-graph demo. Ground truth:+2 SQLi (one unauth+interprocedural), 1 XSS (interprocedural), 1 LFI,+1 unserialize, 1 CSRF (missing nonce) — hidden among ~60 benign helper files.+Usage: make_demo_plugin.py <dir> (default ./acme-plugin)+"""+import os, random, sys+root = sys.argv[1] if len(sys.argv) > 1 else "./acme-plugin"+inc = os.path.join(root, "includes"); os.makedirs(inc, exist_ok=True); random.seed(3)+FILES = {+ "acme.php": """<?php+/* Plugin Name: Acme Tools */+add_action('wp_ajax_acme_search', 'acme_ajax_search');+add_action('wp_ajax_nopriv_acme_search', 'acme_ajax_search');+add_action('wp_ajax_acme_delete', 'acme_delete_item');+add_action('admin_post_acme_save', 'acme_save_settings');+add_action('init', 'acme_show_widget');+add_action('wp_ajax_acme_import', 'acme_import_data');+""",+ "includes/search.php": """<?php+function acme_ajax_search() {+ $term = $_GET['term']; // taint source+ return acme_find_items($term); // flows to db.php+}+""",+ "includes/db.php": """<?php+function acme_find_items($needle) {+ global $wpdb;+ return $wpdb->get_results("SELECT * FROM {$wpdb->prefix}items WHERE name = '$needle'");+}+function acme_delete_item() {+ global $wpdb;+ $wpdb->query("DELETE FROM {$wpdb->prefix}items WHERE id = " . $_POST['id']);+}+""",+ "includes/render.php": """<?php+function acme_show_widget() {+ $title = $_REQUEST['title']; // taint source+ acme_render_box($title);+}+function acme_render_box($text) {+ echo "<div class='acme-box'>" . $text . "</div>"; // xss sink+}+""",+ "includes/admin.php": """<?php+function acme_save_settings() {+ update_option('acme_opts', $_POST['opts']); // state change, no nonce -> CSRF+}+function acme_load_template() {+ include($_GET['tpl'] . '.php'); // LFI+}+""",+ "includes/importer.php": """<?php+function acme_import_data() {+ return unserialize($_POST['payload']); // object injection+}+""",+}+for rel, code in FILES.items():+ open(os.path.join(root, rel), "w").write(code)+for i in range(60):+ fns = "\n".join(+ f"function acme_util_{i}_{j}($x) {{\n return esc_html(sanitize_text_field($x));\n}}"+ for j in range(random.randint(2, 5)))+ open(os.path.join(inc, f"util_{i:02d}.php"), "w").write("<?php\n" + fns + "\n")+n = sum(len(f) for _, _, f in os.walk(root))+print(f"wrote {n} files to {root}/ (6 ground-truth vulnerabilities among ~60 benign files)")diff --git a/docs/research/ast-graph-vuln-detection.md b/docs/research/ast-graph-vuln-detection.mdnew file mode 100644index 000000000..be6903eda--- /dev/null+++ b/docs/research/ast-graph-vuln-detection.md@@ -0,0 +1,161 @@+# Research: AST + graph + FTS for AI vulnerability finding, at codebase scale++**Status:** working prototype, verified on a realistic WordPress plugin. See+`docs/examples/ast-vuln-graph/` to reproduce every number below.++## The problem++An AI is good at judging whether a specific piece of code is exploitable. It is+bad at two things that vulnerability finding requires:++1. **Scale.** A real WordPress install is 100k+ lines across core and plugins.+ It does not fit in a context window, and "load it all and look for bugs" is+ both impossible and, where partial, expensive.+2. **Reach.** The interesting bugs are *interprocedural*: a request value read+ in one function, passed through a helper, and reaching a `$wpdb` query in a+ different file. A per-file scan (grep, or single-file semgrep rules) sees the+ source and the sink as unrelated. It also can't reason about *absence* —+ e.g. a state-changing admin handler with no nonce check (CSRF).++So the two naive options both fail: **full-context load** doesn't scale, and+**grep/per-file matching** misses the real bugs and drowns you in false hits+(every `$wpdb` use, every `$_GET`).++## The approach++Split precision from navigation, and let each layer do what it's good at.++```+ PHP source+ │ parse (phply / tree-sitter)+ ▼+ AST ──► taint GRAPH ← precision: interprocedural source→sink,+ │ (functions, reachability, sanitizer-on-path, nonce-absence+ │ call edges,+ │ sources/sinks/+ │ sanitizers,+ │ hook entry points)+ ▼+ findings + function facts ──► XERJ index ← navigation: FTS / semantic+ │ search + keyword filters+ ▼ (nopriv=true, sinks=sql, …)+ AI reviews ONLY the code on flagged paths ← judgement: confirm exploitability,+ cite file:line+```++Three layers:++1. **AST → taint graph (precision).** Parse every file, record per function:+ the request sources it reads (`$_GET/$_POST/$_REQUEST/…`), the dangerous+ sinks it hits (`$wpdb->query`, `echo`, `include`, `unserialize`, state+ changes like `update_option`), the sanitizers present (`esc_html`,+ `sanitize_*`, `$wpdb->prepare`, `wp_verify_nonce`), and its call edges. Then+ walk the call graph from every source-bearing function; if a sink is reached+ with no sanitizer on the path, that's a finding — **across function and file+ boundaries.** Hook wiring (`add_action('wp_ajax_nopriv_…')`) marks+ unauthenticated entry points.++2. **XERJ index (navigation).** Store the findings and the function facts as+ documents — the fact text is searchable (FTS/semantic), and graph properties+ (`nopriv`, `sinks`, `entry`) are keyword-filterable. An AI agent can now ask,+ in plain language, "unauthenticated handlers that reach a SQL query" and get+ the exact functions, or filter `nopriv:true AND sinks:sql`.++3. **AI review (judgement).** The AI reads only the code on the flagged paths+ and confirms exploitability with a `file:line` citation.++## What was verified++Reproducible in `docs/examples/ast-vuln-graph/` (a realistic 66-file WP plugin+with 6 planted vulnerabilities among ~60 benign helper files):++| metric | result |+|---|--:|+| planted vulnerabilities | 6 |+| **found by the AST graph** | **6 / 6** |+| — of which *interprocedural* (source and sink in different files) | 2 (SQLi, XSS) |+| — of which *unauthenticated-critical* (nopriv hook → SQL sink) | 1 |+| — of which *absence property* (state change, no nonce) | 1 (CSRF) |+| tokens to review the flagged paths | ~412 |+| tokens to load the whole plugin | ~5,491 |+| **reduction** | **~13×** (and it grows without bound as the codebase grows) |++The critical finding — `acme_ajax_search → acme_find_items [UNAUTH]` — requires+**all three graphs at once**: the *hook* graph (the entry is `wp_ajax_nopriv`,+so unauthenticated), the *call* graph (source and sink are in different files),+and *taint* (the `$_GET` value reaches `$wpdb->get_results` with no+`prepare`/sanitizer). No single-file tool produces it.++### The finding that shaped the architecture++The first cut indexed raw function text and let the AI query it with FTS. Asked+for "echo request input without escaping," FTS returned two **benign** helper+functions — because they contain `esc_html`, and the words matched. **FTS over+raw code is noisy for security.** The fix is the ordering above: the *graph*+decides what's a real finding; FTS/semantic search only navigates the+graph-verified findings. Precision comes from the AST; recall-friendly natural+language comes from XERJ. Neither alone is enough.++## Why this beats grep and per-file semgrep++- **grep `$wpdb`** → every DB call, no reachability, no taint. On the demo it+ flags the file but can't tell the injectable query from a prepared one, and+ never links the cross-file source.+- **per-file semgrep** → catches direct source→sink *inside one function*, but+ the interprocedural SQLi and XSS here span files; connecting them needs the+ call graph (semgrep's interprocedural analysis is limited / paid).+- **This** → 6/6 including the interprocedural, unauth, and absence cases, and+ it hands the AI ~13× less to read.++## Design for real WordPress scale++The prototype is a plugin; core + plugins is the target. The design carries over:++- **Extraction is per-file and embarrassingly parallel.** Parse each file to+ function facts independently; a 100k-line tree is a fan-out job, not a+ whole-program load. Incremental: re-parse only changed files.+- **The taint model is data, not code.** Sources, sinks, sanitizers, and+ state-changers are per-framework lists (`docs/examples/ast-vuln-graph/extract_ast.py`+ has the WP set). Add React's `dangerouslySetInnerHTML`, Java's+ `Runtime.exec`, Django's `.raw()`, etc.+- **Findings are the unit of work.** Index findings (path + severity + unauth+ flag + the code on the path) as first-class XERJ documents. The agent queries+ findings, not raw code — severity-ranked, filterable, and each one already+ carries the minimal code to review.+- **XERJ is the right store** because it already unifies keyword filters+ (`nopriv`, `sinks`), full-text and semantic search, and returns chunked code+ with `file:line` — one index answers every query shape an audit needs, and the+ same index holds the docs, configs, and SQL in the same repo.++## Honest limitations++This is triage that finds *more real bugs with far fewer tokens*, not a sound+analyzer. Be clear about what it is not:++- **Static approximation.** Taint follows call edges and direct argument flow;+ it does not model data flow through arrays/objects, aliasing, or dynamic+ dispatch. It will miss flows that launder taint through a `$GLOBALS` array or+ a variable-variable, and it can over-report when a value is validated in a way+ the name-based sanitizer list doesn't recognize.+- **Sanitizer detection is name-based.** It trusts `esc_html`/`prepare` by name;+ it does not check that the *right* escaper is used for the *context* (a+ classic real bug: `esc_html` on a value placed inside an HTML attribute).+- **CSRF/nonce is heuristic** — "state change reachable from an entry with no+ nonce call anywhere on the path." Real nonce logic can be conditional.+- **Parser coverage.** phply is solid but not 100% on the newest PHP syntax;+ a file that fails to parse is skipped (and should be reported, not silently+ dropped — the same loud-skip rule autoindex needs).+- **Every finding needs confirmation.** The point is to shrink what the AI (and+ human) read so they *can* reason about exploitability — not to auto-file CVEs.++## Concrete next steps for XERJ++1. **Ship an AST-aware code extractor in `autoindex`** — chunk code by function+ (not fixed line windows), and store call edges + taint facts as fields, so+ `xerj autoindex ./code` produces the graph-ready index directly.+2. **Findings as a first-class index** with a severity/route schema, so the+ agent loop is "query findings → pull path code → confirm."+3. **Multi-language via tree-sitter**, reusing the per-framework taint lists.+4. **Loud skips** — a file that fails to parse must be reported (a silently+ dropped file in a security audit is the worst-case), matching the+ autoindex honesty rule.