Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/web-quality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,8 @@ jobs:
- run: npx --yes tsx scripts/conversation-eval.ts --distractors --check
- run: npx --yes tsx scripts/learning-eval.ts --check
- run: npx --yes tsx scripts/learning-eval.ts --distractors --check
- name: CoSQA code search (search bar vs BM25)
run: |
git clone --depth 1 --filter=blob:none --sparse https://github.com/microsoft/CodeXGLUE /tmp/cxg
git -C /tmp/cxg sparse-checkout set Text-Code/NL-code-search-WebQuery/CoSQA
COSQA_DIR=/tmp/cxg/Text-Code/NL-code-search-WebQuery/CoSQA npx --yes tsx scripts/cosqa-bench.ts --check
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,19 @@ Three loops improve IntelliRAG as people use it. Each is measured on held-out da

Experience is the "file good answers back" step of [Karpathy's LLM-wiki pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f), done per passage: the source is never edited, and links go stale when the passage they learned about changes. Agents get the same memory through the MCP server's `feedback` tool. It is kept per repository, so a repo keeps learning across sessions.

## Search like GitHub code search

Press ⌘K (Ctrl+K) to search every indexed source instantly. It splits identifiers
(`parseJSONResponse` matches "parse json response"), weights function names and
docstrings, and takes operators: `path:src/queue`, `lang:ts`, `sym:resume`,
`kind:prose`, `"exact words"`, `-word`. Results show the matching lines
highlighted, with "did you mean" for typos and completions from your sources.
The same engine answers `GET /api/search?q=…&corpus=…`.

On CoSQA (313 real web queries, 6,267 Python functions) it scores 46.4 nDCG@10
against 42.9 for plain BM25, with no model. Details and an honest comparison with
dense retrievers: [eval/code-search](eval/code-search/README.md).

## Research behind the design

| Paper | What we took | Status here |
Expand Down
47 changes: 47 additions & 0 deletions eval/code-search/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Code search on CoSQA

The search bar (⌘K in the app, `GET /api/search`) ranks passages with
`web/src/lib/rag/code-search.ts`. This folder measures it on **CoSQA**
(Huang et al., ACL 2021): real Bing queries such as "python remove all empty
items in list" against all 6,267 unique Python functions in the dataset. The
313 dev queries labelled as answered by a function are scored by where that
function ranks.

Settings were tuned on 500 training queries only (`--tune`). The learned
associations come from CoSQA training pairs only; dev queries are never seen.

| Arm | nDCG@10 | MRR@10 | R@1 | R@5 | R@10 |
|---|---|---|---|---|---|
| BM25 with IntelliRAG's prose tokenizer | 42.86 | 37.08 | 27.16 | 52.08 | 61.34 |
| + identifier-aware tokens (`parseJSON` → parse, json) | 45.49 | 39.24 | 27.80 | 55.27 | 65.50 |
| + name and docstring fields (BM25F) | 45.82 | 39.83 | 27.80 | 53.99 | 64.86 |
| tried and left off: developer synonym lexicon | 44.18 | 38.33 | 26.20 | 52.72 | 62.62 |
| tried and left off: pseudo-relevance feedback (RM3) | 44.14 | 37.33 | 25.88 | 53.04 | 66.13 |
| **+ learned query→code associations (the search bar)** | **46.42** | **39.91** | 26.20 | **59.42** | **66.77** |

+3.56 nDCG@10 and +7.3 R@5 over plain BM25, with no model and no GPU. R@1 dips:
associations widen recall more than they sharpen the very top.

**How this compares, honestly.** These are lexical numbers. Dense code
embeddings do better on CoSQA-style queries: on NanoCoIR's CosQA (the same
6,267 functions, a different 50-query sample) BM25 scores 30.5 nDCG@10 and
a dense model 67.3. CoIR's full CosQA leaderboard tops out at 36.3 on its own
query split. The splits differ, so none of these numbers are directly
comparable to the table above. IntelliRAG fuses this lexical ranking with
embeddings when an embedding key is set; the benchmark here is the part that
runs with no key.

In the product the associations are learned from questions people confirmed
a passage answers (the experience log), so search sharpens on your own sources
the more the app is used.

Reproduce, from `web/`:

```bash
git clone --depth 1 --filter=blob:none --sparse https://github.com/microsoft/CodeXGLUE /tmp/cxg
git -C /tmp/cxg sparse-checkout set Text-Code/NL-code-search-WebQuery/CoSQA
COSQA_DIR=/tmp/cxg/Text-Code/NL-code-search-WebQuery/CoSQA npx tsx scripts/cosqa-bench.ts --check
```

CI runs the same check: the search bar must stay 2+ points above plain BM25
and match `cosqa-results.json`.
68 changes: 68 additions & 0 deletions eval/code-search/cosqa-results.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"benchmark": "CoSQA dev (label 1) vs all unique CoSQA functions",
"queries": 313,
"documents": 6267,
"settings": {
"k1": 1.2,
"b": 0.75,
"nameWeight": 4,
"docWeight": 2,
"synonymWeight": 0.35,
"prfDocs": 0,
"prfTerms": 8,
"prfWeight": 0.3,
"useLexicon": false,
"associationWeight": 0.35,
"associationsPerTerm": 2
},
"arms": [
{
"arm": "BM25, IntelliRAG prose tokenizer",
"mrr10": 0.370833967239718,
"ndcg10": 0.42856262592410366,
"r1": 0.2715654952076677,
"r5": 0.5207667731629393,
"r10": 0.6134185303514377
},
{
"arm": "+ identifier-aware tokens",
"mrr10": 0.3923842486941529,
"ndcg10": 0.4549075966533442,
"r1": 0.2779552715654952,
"r5": 0.5527156549520766,
"r10": 0.6549520766773163
},
{
"arm": "+ name and docstring fields (BM25F)",
"mrr10": 0.39827957807191017,
"ndcg10": 0.4581641676708342,
"r1": 0.2779552715654952,
"r5": 0.5399361022364217,
"r10": 0.6485623003194888
},
{
"arm": " (tried, off) + developer lexicon",
"mrr10": 0.383252193316091,
"ndcg10": 0.44180910366028336,
"r1": 0.26198083067092653,
"r5": 0.5271565495207667,
"r10": 0.6261980830670927
},
{
"arm": " (tried, off) + pseudo-relevance feedback (RM3)",
"mrr10": 0.37328211369744885,
"ndcg10": 0.44135808902720697,
"r1": 0.25878594249201275,
"r5": 0.5303514376996805,
"r10": 0.6613418530351438
},
{
"arm": "+ learned query→code associations: search bar",
"mrr10": 0.39905040823571175,
"ndcg10": 0.464233407529018,
"r1": 0.26198083067092653,
"r5": 0.5942492012779552,
"r10": 0.6677316293929713
}
]
}
92 changes: 92 additions & 0 deletions web/scripts/cosqa-bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/** The search bar against a public code-search benchmark: CoSQA (Huang et al., ACL 2021).
* Run from web: COSQA_DIR=<CodeXGLUE>/Text-Code/NL-code-search-WebQuery/CoSQA npx tsx scripts/cosqa-bench.ts [--write]
*
* Real Bing queries ("python remove all empty items in list") against 6,267
* Python functions: every unique function in CoSQA. That is the same document
* set as NanoCoIR's CosQA task. Queries are the 313 dev queries labelled as
* answered by their function; scoring is the rank of that function. Settings
* were tuned only on 500 training queries (--tune), never on dev.
* The data isn't committed; CI fetches it from microsoft/CodeXGLUE.
*/
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { BM25Index } from '../src/lib/rag/bm25';
import { CodeSearchIndex, DEFAULT_SEARCH, learnAssociations, type Associations, type SearchOptions } from '../src/lib/rag/code-search';

const dir = process.env.COSQA_DIR;
if (!dir) { console.error('Set COSQA_DIR to CodeXGLUE/Text-Code/NL-code-search-WebQuery/CoSQA'); process.exit(2); }
type Pair = { idx: string; doc: string; code: string; label: number };
const all: Pair[] = JSON.parse(readFileSync(resolve(dir, 'cosqa-all.json'), 'utf8'));
const dev: Pair[] = JSON.parse(readFileSync(resolve(dir, 'cosqa-dev.json'), 'utf8'));
const codes = [...new Set([...all, ...dev].map((p) => p.code))];
const idOf = new Map(codes.map((c, i) => [c, `f${i}`]));
const docs = codes.map((c, i) => ({ id: `f${i}`, body: c, lang: 'py', kind: 'code' as const }));

const devQ = dev.filter((p) => p.label === 1).map((p) => ({ q: p.doc, gold: idOf.get(p.code)! }));
// Training queries for tuning: a fixed, evenly spaced sample, disjoint from dev.
const trainPos = all.filter((p) => p.label === 1 && p.idx.startsWith('cosqa-train'));
const trainQ = Array.from({ length: 500 }, (_, i) => trainPos[Math.floor((i * trainPos.length) / 500)]!).map((p) => ({ q: p.doc, gold: idOf.get(p.code)! }));

function metrics(rank: (q: string) => string[], qs: Array<{ q: string; gold: string }>) {
let mrr = 0, ndcg = 0, r1 = 0, r5 = 0, r10 = 0;
for (const { q, gold } of qs) {
const i = rank(q).slice(0, 10).indexOf(gold);
if (i < 0) continue;
mrr += 1 / (i + 1); ndcg += 1 / Math.log2(i + 2);
if (i < 1) r1++; if (i < 5) r5++; r10++;
}
const n = qs.length;
return { mrr10: mrr / n, ndcg10: ndcg / n, r1: r1 / n, r5: r5 / n, r10: r10 / n };
}

const plain = new BM25Index(docs.map((d) => ({ id: d.id, text: d.body })));
// Learned associations from CoSQA's training pairs only (dev is never seen).
const assoc: Associations = learnAssociations(all.filter((p) => p.label === 1 && p.idx.startsWith('cosqa-train')).map((p) => ({ query: p.doc, doc: p.code })));
const engine = (opts: Partial<SearchOptions>, learned = false) => { const ix = new CodeSearchIndex(docs, { ...DEFAULT_SEARCH, ...opts }, learned ? assoc : null); return (q: string) => ix.search(q, 10).map((h) => h.id); };

if (process.argv.includes('--tune')) {
// Coarse grid on training queries only.
// Tuning queries are held out of the association table, so tuning measures generalisation.
const tuneIds = new Set(trainQ.map((x) => x.q));
const assocTune = learnAssociations(all.filter((p) => p.label === 1 && p.idx.startsWith('cosqa-train') && !tuneIds.has(p.doc)).map((p) => ({ query: p.doc, doc: p.code })));
for (const nameWeight of [2, 4]) for (const synonymWeight of [0, 0.35]) for (const associationWeight of [0, 0.2, 0.35, 0.5, 0.8]) for (const associationsPerTerm of [2, 4, 8]) {
const ix = new CodeSearchIndex(docs, { ...DEFAULT_SEARCH, nameWeight, synonymWeight, associationWeight, associationsPerTerm, prfDocs: 0 }, assocTune);
const m = metrics((q) => ix.search(q, 10).map((h) => h.id), trainQ);
console.log(JSON.stringify({ nameWeight, synonymWeight, associationWeight, associationsPerTerm }), m.ndcg10.toFixed(4));
}
process.exit(0);
}

const arms: Array<[string, (q: string) => string[]]> = [
['BM25, IntelliRAG prose tokenizer', (q) => plain.search(q, 10).map((h) => h.id)],
['+ identifier-aware tokens', engine({ nameWeight: 1, docWeight: 1 })],
['+ name and docstring fields (BM25F)', engine({})],
[' (tried, off) + developer lexicon', engine({ useLexicon: true })],
[' (tried, off) + pseudo-relevance feedback (RM3)', engine({ prfDocs: 8 })],
['+ learned query→code associations: search bar', engine({}, true)],
];
const pct = (x: number) => (100 * x).toFixed(2);
console.log(`CoSQA · ${devQ.length} dev queries · ${docs.length} functions`);
console.log('arm'.padEnd(42), 'nDCG@10 MRR@10 R@1 R@5 R@10');
const results: any[] = [];
for (const [name, fn] of arms) {
const m = metrics(fn, devQ);
results.push({ arm: name, ...m });
console.log(name.padEnd(42), pct(m.ndcg10).padEnd(8), pct(m.mrr10).padEnd(7), pct(m.r1).padEnd(6), pct(m.r5).padEnd(6), pct(m.r10));
}
if (process.argv.includes('--write')) {
const out = resolve(import.meta.dirname, '../../eval/code-search');
mkdirSync(out, { recursive: true });
writeFileSync(out + '/cosqa-results.json', JSON.stringify({ benchmark: 'CoSQA dev (label 1) vs all unique CoSQA functions', queries: devQ.length, documents: docs.length, settings: DEFAULT_SEARCH, arms: results }, null, 2) + '\n');
}
if (process.argv.includes('--check')) {
// The search bar must clearly beat plain BM25 and match the committed numbers.
const committed = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../eval/code-search/cosqa-results.json'), 'utf8'));
const bar = results.at(-1)!, base = results[0]!;
const was = committed.arms.at(-1).ndcg10;
const fails: string[] = [];
if (bar.ndcg10 - base.ndcg10 < 0.02) fails.push(`search bar nDCG@10 ${pct(bar.ndcg10)} is not 2 points above plain BM25 ${pct(base.ndcg10)}`);
if (Math.abs(bar.ndcg10 - was) > 0.005) fails.push(`search bar nDCG@10 ${pct(bar.ndcg10)} drifted from committed ${pct(was)}; rerun with --write if intended`);
if (fails.length) { console.error(fails.join('\n')); process.exit(1); }
console.log('check passed');
}
17 changes: 17 additions & 0 deletions web/src/components/console.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
LoaderCircle,
Lock,
Plus,
Search,
ShieldAlert,
X,
} from "lucide-react";
Expand Down Expand Up @@ -72,6 +73,7 @@ import type {
StorageStatus,
} from "@/lib/rag/types";
import { cn } from "@/lib/utils";
import { SearchPalette } from "@/components/rag/search-palette";

type Snapshot = Awaited<ReturnType<typeof getLabSnapshot>>;

Expand Down Expand Up @@ -164,6 +166,7 @@ export function Console({ initial }: { initial: Snapshot }) {
const [desktop, setDesktop] = useState(false);
useEffect(() => { const media = matchMedia('(min-width: 1024px)'); const update = () => setDesktop(media.matches); update(); media.addEventListener('change', update); return () => media.removeEventListener('change', update); }, []);
const [corpusOpen, setCorpusOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const [auditOpen, setAuditOpen] = useState(false);
const [mode, setMode] = useState<RetrievalMode>("hybrid");
const [topK, setTopK] = useState(5);
Expand Down Expand Up @@ -289,6 +292,14 @@ export function Console({ initial }: { initial: Snapshot }) {
else el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
}, [messages]);

useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key.toLowerCase() === "k" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); setSearchOpen((o) => !o); }
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);

useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== "/" || e.metaKey || e.ctrlKey || e.altKey) return;
Expand Down Expand Up @@ -615,6 +626,11 @@ export function Console({ initial }: { initial: Snapshot }) {
<span data-tour="tour-view">
<ViewToggle value={view} onChange={setView} />
</span>
<button type="button" onClick={() => setSearchOpen(true)} aria-label="Search sources (Ctrl+K)" className="inline-flex min-h-9 items-center gap-2 rounded-sm border border-border px-2.5 text-sm text-muted hover:border-fg/30 hover:text-fg">
<Search className="size-4" aria-hidden />
<span className="hidden md:inline">Search code</span>
<kbd className="hidden font-mono text-[11px] text-subtle lg:inline">⌘K</kbd>
</button>
<Button variant="ghost" size="sm" className="hidden sm:inline-flex" data-tour="tour-sources" aria-expanded={corpusOpen} onClick={() => setCorpusOpen(!corpusOpen)}>Sources</Button>
<Button variant="ghost" size="sm" className="hidden sm:inline-flex" data-tour="tour-evidence" aria-expanded={auditOpen} onClick={() => setAuditOpen(!auditOpen)}>Evidence</Button>
<a href="/architecture.html" className="hidden min-h-11 items-center px-2 text-sm text-muted underline-offset-4 hover:text-fg hover:underline xl:inline-flex">Architecture</a>
Expand All @@ -631,6 +647,7 @@ export function Console({ initial }: { initial: Snapshot }) {
</div>
</header>

<SearchPalette open={searchOpen} onClose={() => setSearchOpen(false)} corpus={corpus} />
<DemoBanner posture={posture} />

{!hasKey && !demo && (
Expand Down
Loading
Loading