Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(docs): full-text docs search shared between builder and runtime

nirholasbee3170c2c84
diff --git a/.gitignore b/.gitignore
index 9b5413477..a76ff71a3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -430,3 +430,9 @@ new_changelog.json
# harness can never be swept into a commit by a `git add -A` from another
# session. Put anything you intend to keep in scripts/.
/scratch-*.mjs
+
+# Documentation search index: generated from docs/**/*.md by
+# scripts/build-docs-search-index.mjs (prebuild + postinstall). It is ~1.4 MB
+# and rewritten by every docs edit, so committing it would grow the repo by a
+# fresh copy per docs change while adding nothing a build cannot reproduce.
+public/docs-search-index.json
diff --git a/docs/index.html b/docs/index.html
index 787883151..f50752c6e 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -29,6 +29,14 @@
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css"
/>
<link rel="stylesheet" href="/docs-live.css" />
+ <!-- Cookbook recipes and tutorials both use `figure:` directives, and both
+ render here as well as in the standalone viewers. Without the resolver
+ this shell paints <img src="figure:img:…">, which is a broken image and
+ an ERR_UNKNOWN_URL_SCHEME per figure. Same files the tutorial viewer
+ loads, so a figure looks identical on every surface. -->
+ <link rel="stylesheet" href="/tutorial-figures.css" />
+ <script src="/tutorial-figures.js"></script>
+ <script src="/model-viewer-meshopt.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<style>
@@ -276,6 +284,87 @@
pointer-events: none;
opacity: 0.35;
}
+ .sidebar-search kbd {
+ position: absolute;
+ right: 8px;
+ top: 50%;
+ transform: translateY(-50%);
+ pointer-events: none;
+ font: 600 10px/1 var(--font-mono, ui-monospace, monospace);
+ color: rgba(255, 255, 255, 0.28);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 3px 5px;
+ transition: opacity 0.15s;
+ }
+ .sidebar-search input:focus ~ kbd,
+ .sidebar-search input:not(:placeholder-shown) ~ kbd {
+ opacity: 0;
+ }
+
+ /* Full-text results from the docs search index. Rendered above the
+ filtered page list because a content match is almost always what
+ someone typing a question is looking for. */
+ .sidebar-results {
+ margin: 0 var(--space-sm) var(--space-md);
+ }
+ .sidebar-results[hidden] {
+ display: none;
+ }
+ .sidebar-results-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.32);
+ padding: 0 4px 6px;
+ }
+ .sidebar-hit {
+ display: block;
+ padding: 7px 9px;
+ border-radius: var(--radius-md);
+ text-decoration: none;
+ border: 1px solid transparent;
+ transition: background 0.12s, border-color 0.12s;
+ }
+ .sidebar-hit:hover,
+ .sidebar-hit:focus-visible,
+ .sidebar-hit[aria-selected='true'] {
+ background: rgba(139, 92, 246, 0.1);
+ border-color: rgba(139, 92, 246, 0.35);
+ outline: none;
+ }
+ .sidebar-hit-title {
+ display: block;
+ font-size: var(--text-sm);
+ color: #e6e6e6;
+ line-height: 1.35;
+ }
+ .sidebar-hit-title mark {
+ background: rgba(139, 92, 246, 0.28);
+ color: #fff;
+ border-radius: 2px;
+ padding: 0 1px;
+ }
+ .sidebar-hit-doc {
+ display: block;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.38);
+ margin-top: 2px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .sidebar-results-note {
+ padding: 4px 5px 0;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.34);
+ line-height: 1.5;
+ }
.sidebar-section {
margin-bottom: var(--space-md);
@@ -805,11 +894,24 @@
<input
type="text"
id="search-input"
- placeholder="Search…"
+ placeholder="Search the docs…"
autocomplete="off"
spellcheck="false"
+ role="combobox"
+ aria-expanded="false"
+ aria-controls="content-results"
+ aria-autocomplete="list"
+ aria-label="Search the documentation"
/>
+ <kbd>/</kbd>
</div>
+ <div
+ class="sidebar-results"
+ id="content-results"
+ role="listbox"
+ aria-label="Documentation content matches"
+ hidden
+ ></div>
<nav id="sidebar-nav"></nav>
</aside>
@@ -1110,9 +1212,33 @@
if (!res.ok) throw new Error(res.status);
const md = await res.text();
- const html = marked.parse(md);
+ // Turn `figure:` directives into inert slots BEFORE parsing. Left as
+ // <img src="figure:…">, the browser fires a request the moment the
+ // markup lands and logs ERR_UNKNOWN_URL_SCHEME for every figure.
+ const html = marked.parse(
+ window.tutorialFigures ? window.tutorialFigures.preprocess(md) : md,
+ );
content.innerHTML = html;
+ // Fill those slots with the captured media, the live 3D viewers,
+ // and the shared lightbox.
+ window.tutorialFigures?.mount(content);
+
+ // Freshness: has anyone checked this page against the code lately?
+ // Mounted above the article, before the heavier enhancers, because
+ // a reader deciding whether to trust the page should see it first.
+ // Fails silently: a missing report must never cost the reader the
+ // documentation itself.
+ const freshHost = document.createElement('div');
+ content.prepend(freshHost);
+ import('/doc-freshness.js')
+ .then((m) => m.mountBadge(freshHost, m.docPathForSlug(path)))
+ .catch(() => freshHost.remove());
+
+ // Markdown images become captioned, zoomable figures sized from
+ // the media manifest, so the article never reflows on decode.
+ window.DocFigures?.upgrade(content);
+
renderPageTools(path, md);
content.querySelectorAll('pre code').forEach(block => {
@@ -1208,10 +1334,207 @@
window.addEventListener('hashchange', navigate);
- document.getElementById('search-input').addEventListener('input', e => {
- buildSidebar(e.target.value);
+ // ── Full-text search over the docs corpus ────────────────────────────
+ //
+ // The sidebar filter has always matched page TITLES, which only helps a
+ // reader who already knows what the page is called. The engine in
+ // /docs-search.js answers the other question: "which page says this?" -
+ // against an index of every heading and paragraph under docs/.
+ //
+ // It is loaded on the first keystroke, never on page load: the index is
+ // ~1.4 MB and most readers arrive to read, not to search.
+ const searchInput = document.getElementById('search-input');
+ const resultsBox = document.getElementById('content-results');
+ const MIN_QUERY = 2;
+ const SEARCH_DEBOUNCE_MS = 90;
+ const MAX_HITS = 8;
+
+ let enginePromise = null;
+ let searchTimer = null;
+ let activeHit = -1;
+ let lastQuery = '';
+
+ function loadEngine() {
+ if (enginePromise) return enginePromise;
+ enginePromise = new Promise(resolve => {
+ if (window.twsDocsSearch) return resolve(window.twsDocsSearch);
+ const script = document.createElement('script');
+ script.src = '/docs-search.js';
+ script.onload = () => resolve(window.twsDocsSearch || null);
+ // A missing engine degrades to title filtering, which is exactly
+ // what this page did before. Nothing user-facing breaks.
+ script.onerror = () => resolve(null);
+ document.head.appendChild(script);
+ }).then(async engine => {
+ if (!engine) return null;
+ const ok = await engine.ready();
+ return ok ? engine : null;
+ });
+ return enginePromise;
+ }
+
+ function escapeHtml(text) {
+ return String(text).replace(
+ /[&<>"']/g,
+ c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+ }
+
+ // Highlight the terms that actually earned the match, longest first so
+ // "wallet" wins over "wall" and the shorter term cannot split the tag it
+ // is nested inside.
+ function highlight(text, matched) {
+ const safe = escapeHtml(text);
+ const terms = (matched || [])
+ .filter(t => t && t.length >= MIN_QUERY)
+ .sort((a, b) => b.length - a.length)
+ .slice(0, 8)
+ .map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ if (!terms.length) return safe;
+ return safe.replace(new RegExp('(' + terms.join('|') + ')', 'gi'), '<mark>$1</mark>');
+ }
+
+ function clearResults() {
+ resultsBox.hidden = true;
+ resultsBox.innerHTML = '';
+ searchInput.setAttribute('aria-expanded', 'false');
+ searchInput.removeAttribute('aria-activedescendant');
+ activeHit = -1;
+ }
+
+ function renderNote(message) {
+ resultsBox.hidden = false;
+ resultsBox.innerHTML = '<p class="sidebar-results-note">' + escapeHtml(message) + '</p>';
+ searchInput.setAttribute('aria-expanded', 'false');
+ }
+
+ function renderHits(hits, query) {
+ if (!hits.length) {
+ renderNote('No content matches “' + query + '”. Matching page names are listed below.');
+ return;
+ }
+ const head =
+ '<div class="sidebar-results-head"><span>In page content</span><span>' +
+ hits.length +
+ '</span></div>';
+ resultsBox.innerHTML =
+ head +
+ hits
+ .map(
+ (hit, i) =>
+ '<a class="sidebar-hit" role="option" aria-selected="false" id="docs-hit-' +
+ i +
+ '" href="' +
+ escapeHtml(hit.url) +
+ '"><span class="sidebar-hit-title">' +
+ highlight(hit.heading || hit.docTitle, hit.matched) +
+ '</span><span class="sidebar-hit-doc">' +
+ escapeHtml(hit.docTitle) +
+ '</span></a>',
+ )
+ .join('');
+ resultsBox.hidden = false;
+ searchInput.setAttribute('aria-expanded', 'true');
+ activeHit = -1;
+ searchInput.removeAttribute('aria-activedescendant');
+ }
+
+ function moveActive(delta) {
+ const rows = [...resultsBox.querySelectorAll('.sidebar-hit')];
+ if (!rows.length) return false;
+ if (activeHit >= 0 && rows[activeHit]) rows[activeHit].setAttribute('aria-selected', 'false');
+ activeHit = (activeHit + delta + rows.length + 1) % (rows.length + 1);
+ // The extra slot is "nothing selected", so ArrowUp from the first row
+ // returns focus to the query rather than wrapping to the bottom.
+ if (activeHit === rows.length) {
+ activeHit = -1;
+ searchInput.removeAttribute('aria-activedescendant');
+ return true;
+ }
+ const row = rows[activeHit];
+ row.setAttribute('aria-selected', 'true');
+ row.scrollIntoView({ block: 'nearest' });
+ searchInput.setAttribute('aria-activedescendant', row.id);
+ return true;
+ }
+
+ async function runSearch(query) {
+ const trimmed = query.trim();
+ lastQuery = trimmed;
+ if (trimmed.length < MIN_QUERY) {
+ clearResults();
+ return;
+ }
+ const engine = await loadEngine();
+ // The reader kept typing while the index loaded; that keystroke's own
+ // search is already on its way.
+ if (lastQuery !== trimmed) return;
+ if (!engine) {
+ renderNote('Content search is unavailable. Page names still filter below.');
+ return;
+ }
+ renderHits(engine.query(trimmed, MAX_HITS), trimmed);
+ }
+
+ searchInput.addEventListener('input', e => {
+ const value = e.target.value;
+ buildSidebar(value);
+ clearTimeout(searchTimer);
+ searchTimer = setTimeout(() => runSearch(value), SEARCH_DEBOUNCE_MS);
+ });
+
+ searchInput.addEventListener('keydown', e => {
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ if (moveActive(e.key === 'ArrowDown' ? 1 : -1)) e.preventDefault();
+ return;
+ }
+ if (e.key === 'Enter') {
+ const row = resultsBox.querySelectorAll('.sidebar-hit')[activeHit];
+ if (row) {
+ e.preventDefault();
+ row.click();
+ }
+ return;
+ }
+ if (e.key === 'Escape') {
+ if (resultsBox.hidden && !searchInput.value) return;
+ e.preventDefault();
+ searchInput.value = '';
+ buildSidebar('');
+ clearResults();
+ }
+ });
+
+ resultsBox.addEventListener('click', () => {
+ // Navigation is by hash, so the result list would otherwise stay open
+ // over the page the reader just chose.
+ clearResults();
+ if (window.innerWidth <= 860) {
+ document.getElementById('sidebar').classList.remove('open');
+ document.getElementById('sidebar-overlay').classList.remove('visible');
+ }
+ });
+
+ // "/" is the near-universal focus-search shortcut. Ignored while the
+ // reader is typing somewhere else, so it never swallows a real slash.
+ document.addEventListener('keydown', e => {
+ if (e.key !== '/' || e.metaKey || e.ctrlKey || e.altKey) return;
+ const tag = (e.target.tagName || '').toLowerCase();
+ if (tag === 'input' || tag === 'textarea' || e.target.isContentEditable) return;
+ e.preventDefault();
+ document.getElementById('sidebar').classList.add('open');
+ searchInput.focus();
+ searchInput.select();
});
+ // /docs?q=… runs the search on arrival, so a search result is a URL
+ // someone can send to a colleague.
+ const initialQuery = new URLSearchParams(location.search).get('q');
+ if (initialQuery) {
+ searchInput.value = initialQuery;
+ runSearch(initialQuery);
+ }
+
const fab = document.getElementById('sidebar-fab');
const sidebar = document.getElementById('sidebar');
const overlay = document.getElementById('sidebar-overlay');
diff --git a/public/docs-search.js b/public/docs-search.js
index 48f54a7e3..1e71806ab 100644
--- a/public/docs-search.js
+++ b/public/docs-search.js
@@ -48,6 +48,13 @@
var HEADING_BOOST = 2.2;
var TITLE_BOOST = 1.5;
+ // How hard to favour sections that contain ALL the query's terms over ones
+ // that contain one of them repeatedly. Tuned on real queries against this
+ // corpus: 1 was too weak to beat a single high-frequency term, 2 started
+ // discarding good partial matches when a query included a word we simply do
+ // not use.
+ var COORD_EXPONENT = 1.5;
+
// One document should not be able to fill the result list with five of its
// own sections when four other documents also answer the question.
var MAX_PER_DOC = 2;
@@ -56,8 +63,8 @@
var MAX_TOKEN = 24;
var JUNK_TOKEN = /^(?:[0-9a-f]{8,}|\d{6,})$/;
var STOPWORDS = {};
- ('a an and are as at be been but by for from had has have how i if in into is it its of on or '
- + 'that the their then there these they this to was were what when where which while who will with you your')
+ ('a an and are as at be been but by did do does for from had has have how i if in into is it its me my '
+ + 'of on or our so than that the their then there these they this to us was we were what when where which while who will with you your')
.split(' ')
.forEach(function (w) {
STOPWORDS[w] = true;
@@ -165,16 +172,26 @@
}
}
- function accumulate(scores, termIndex, weight) {
+ function accumulate(scores, coverage, bit, termIndex, weight) {
var weightedIdf = idf(index.dfs[termIndex]) * weight;
var avgLen = index.avgLen || 1;
eachPosting(termIndex, function (sectionId, tf) {
var len = index.sections[sectionId][2] || 1;
var norm = tf + K1 * (1 - B + (B * len) / avgLen);
scores[sectionId] = (scores[sectionId] || 0) + (weightedIdf * (tf * (K1 + 1))) / norm;
+ coverage[sectionId] = (coverage[sectionId] || 0) | bit;
});
}
+ function popcount(mask) {
+ var n = 0;
+ while (mask) {
+ mask &= mask - 1;
+ n++;
+ }
+ return n;
+ }
+
/**
* Rank documentation sections for a query.
*
@@ -196,22 +213,33 @@
var trailingIsPartial = /[a-z0-9]$/i.test(text);
var scores = {};
+ // Which of the query's terms each section actually contains, as a bitmask.
+ // Only the first 31 unique terms get a bit, which no real query reaches.
+ var coverage = {};
var matched = [];
- for (var t = 0; t < unique.length; t++) {
+ var scoredTerms = 0;
+ for (var t = 0; t < unique.length && t < 31; t++) {
var token = unique[t];
+ var bit = 1 << t;
var exact = termId(token);
+ var hitAny = false;
if (exact !== -1) {
- accumulate(scores, exact, 1);
+ accumulate(scores, coverage, bit, exact, 1);
matched.push(token);
+ hitAny = true;
}
if (token === last && trailingIsPartial) {
var expansions = prefixTermIds(token);
for (var e = 0; e < expansions.length; e++) {
if (expansions[e] === exact) continue;
- accumulate(scores, expansions[e], PREFIX_WEIGHT);
+ accumulate(scores, coverage, bit, expansions[e], PREFIX_WEIGHT);
matched.push(terms[expansions[e]]);
+ hitAny = true;
}
}
+ // A term nobody wrote (a typo, a product we do not document) must not
+ // count against every section for lacking it.
+ if (hitAny) scoredTerms++;
}
var ranked = [];
@@ -222,10 +250,24 @@
var doc = index.docs[section[0]];
var heading = (section[1] || '').toLowerCase();
var title = (doc[1] || '').toLowerCase();
- var boost = 1;
+ // Scaled by the FRACTION of the query the heading carries, not
+ // compounded per word. Multiplying once per matched term let a long
+ // heading that happens to contain three common query words outrank the
+ // page actually about the subject by an order of magnitude.
+ var inHeading = 0;
+ var inTitle = 0;
for (var m = 0; m < unique.length; m++) {
- if (heading.indexOf(unique[m]) !== -1) boost *= HEADING_BOOST;
- else if (title.indexOf(unique[m]) !== -1) boost *= TITLE_BOOST;
+ if (heading.indexOf(unique[m]) !== -1) inHeading++;
+ else if (title.indexOf(unique[m]) !== -1) inTitle++;
+ }
+ var of = Math.max(1, scoredTerms);
+ var boost = (1 + ((HEADING_BOOST - 1) * inHeading) / of) * (1 + ((TITLE_BOOST - 1) * inTitle) / of);
+ // Coordination: a section holding every word of the question beats one
+ // holding a single rare word many times. Without this, "fund an agent
+ // wallet" is won by whichever page says "fund" most often rather than
+ // by the page about funding agent wallets.
+ if (scoredTerms > 1) {
+ boost *= Math.pow(popcount(coverage[key] || 0) / scoredTerms, COORD_EXPONENT);
}
ranked.push({ sectionId: sectionId, docId: section[0], score: scores[key] * boost });
}
@@ -234,11 +276,19 @@
});
var perDoc = {};
+ var seenHeading = {};
var out = [];
for (var r = 0; r < ranked.length && out.length < max; r++) {
var hit = ranked[r];
var seen = perDoc[hit.docId] || 0;
if (seen >= MAX_PER_DOC) continue;
+ // Long-form docs are also published split into chapters, so the same
+ // heading legitimately exists in two places. Both are real
+ // destinations, but showing both spends a result slot to say the same
+ // sentence twice: keep whichever ranked higher.
+ var headingKey = (index.sections[hit.sectionId][1] || '').toLowerCase();
+ if (headingKey && seenHeading[headingKey]) continue;
+ seenHeading[headingKey] = true;
perDoc[hit.docId] = seen + 1;
out.push(result(hit));
}
diff --git a/scripts/build-docs-search-index.mjs b/scripts/build-docs-search-index.mjs
index f4a825c9c..d1fad5860 100644
--- a/scripts/build-docs-search-index.mjs
+++ b/scripts/build-docs-search-index.mjs
@@ -35,22 +35,30 @@
*/
import { readdirSync, readFileSync, writeFileSync, renameSync, existsSync } from 'node:fs';
-import { join, relative, dirname } from 'node:path';
+import { join, relative, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const DOCS_DIR = join(ROOT, 'docs');
const OUT_PATH = join(ROOT, 'public', 'docs-search-index.json');
-// docs/ALL.md is the generated concatenation of every other doc. Indexing it
-// would duplicate the entire corpus and let one 6 MB file outrank the real page
-// for every query.
-const SKIP_FILES = new Set(['ALL.md']);
-
-// Sections split on H1/H2 only. H3 splitting was measured at ~7.8k sections
-// against ~3.4k here, and the smaller units lost the surrounding context that
-// makes a result row readable while nearly doubling the artifact.
-const SECTION_HEADING = /^(#{1,2})\s+(.+?)\s*#*\s*$/;
+// Generated aggregates restate the corpus. docs/ALL.md is every other doc
+// concatenated; docs/agent-abilities/ABILITIES.md is a rewrite of
+// FULL-ARTICLE.md. Indexing them lets one file answer for content it does not
+// own, and fills a result list with three copies of the same paragraph.
+//
+// Detection is by the marker generators already write into their own output
+// rather than a curated filename list, so the next generated doc is excluded
+// the day it lands instead of the day someone notices.
+const GENERATED_MARKER = /^<!--\s*GENERATED\b/im;
+const GENERATED_HEAD_LINES = 3;
+
+// Sections split on H1/H2/H3. Splitting only on H1/H2 was measured smaller, but
+// it is wrong: docs that use H3 as their entry level (the whole ux-flows atlas)
+// collapse into one enormous section that then matches every query and answers
+// none of them. Every heading the reader can link to is a heading search can
+// land on.
+const SECTION_HEADING = /^(#{1,3})\s+(.+?)\s*#*\s*$/;
// Below this a "section" is a heading with a sentence fragment under it — a
// stub, a table caption, a see-also. Indexing them adds noise, not answers.
@@ -84,8 +92,8 @@ const JUNK_TOKEN = /^(?:[0-9a-f]{8,}|\d{6,})$/;
// developer corpus ("no code", "off chain", "on chain"), so this covers only
// words that carry no selectivity anywhere.
const STOPWORDS = new Set(
- ('a an and are as at be been but by for from had has have how i if in into is it its of on or '
- + 'that the their then there these they this to was were what when where which while who will with you your')
+ ('a an and are as at be been but by did do does for from had has have how i if in into is it its me my '
+ + 'of on or our so than that the their then there these they this to us was we were what when where which while who will with you your')
.split(' '),
);
@@ -94,7 +102,7 @@ function walkMarkdown(dir, out = []) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
walkMarkdown(full, out);
- } else if (entry.name.endsWith('.md') && !SKIP_FILES.has(relative(DOCS_DIR, full))) {
+ } else if (entry.name.endsWith('.md')) {
out.push(full);
}
}
@@ -250,17 +258,34 @@ export function frontCode(terms) {
return out;
}
-function buildIndex() {
- const files = walkMarkdown(DOCS_DIR);
+/** A generator stamps its own output; the marker sits in the first few lines. */
+export function isGenerated(md) {
+ return GENERATED_MARKER.test(md.split(/\r?\n/, GENERATED_HEAD_LINES).join('\n'));
+}
+
+/**
+ * Build the index in memory. Exported so the test suite can assert on the real
+ * corpus without writing to a worktree other agents are also using.
+ *
+ * @param {string} [dir] documentation root
+ * @returns {object} the artifact that is serialized to public/docs-search-index.json
+ */
+export function buildIndex(dir = DOCS_DIR) {
+ const files = walkMarkdown(dir);
+ const skipped = [];
const docs = [];
const sections = [];
// term -> Map<sectionId, tf>
const posting = new Map();
for (const file of files) {
- const rel = relative(DOCS_DIR, file).replace(/\\/g, '/');
+ const rel = relative(dir, file).replace(/\\/g, '/');
const slug = rel.replace(/\.md$/, '');
const md = readFileSync(file, 'utf8');
+ if (isGenerated(md)) {
+ skipped.push(slug);
+ continue;
+ }
const fallback = slug.split('/').pop().replace(/[-_]+/g, ' ');
const { title, sections: parsed } = splitSections(md, fallback);
if (!parsed.length) continue;
@@ -317,6 +342,9 @@ function buildIndex() {
v: 1,
note: 'Generated by scripts/build-docs-search-index.mjs. Do not edit by hand.',
docCount: docs.length,
+ // Named, not just counted: a doc that silently stops being searchable
+ // because a generator marker appeared in it should be visible here.
+ skippedGenerated: skipped,
sectionCount: sections.length,
avgLen: sections.length ? Math.round((totalTokens / sections.length) * 100) / 100 : 0,
tfBits: TF_BITS,
@@ -336,6 +364,11 @@ function serialize(index) {
return `${JSON.stringify(index)}\n`;
}
+// Importing this module must not build or write anything: the test suite pulls
+// in buildIndex() and the pure helpers directly.
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();
+
+function main() {
const check = process.argv.includes('--check');
const index = buildIndex();
const output = serialize(index);
@@ -361,3 +394,4 @@ if (check) {
`docs-search: ${index.docCount} docs, ${index.sectionCount} sections, ${index.terms.length} terms, ${kb} KB`,
);
}
+}
diff --git a/tests/docs-search.test.js b/tests/docs-search.test.js
new file mode 100644
index 000000000..3015eeb28
--- /dev/null
+++ b/tests/docs-search.test.js
@@ -0,0 +1,267 @@
+// Documentation search: builder + runtime.
+//
+// The two halves of this feature live in different files and different
+// languages of the stack (a node ESM build script, a browser IIFE), but they
+// share one encoding and one tokenizer. Every test here that looks pedantic is
+// guarding a way those two can silently drift apart, because the failure mode
+// is never an exception: it is a search that quietly stops finding things.
+
+import { describe, it, expect, beforeAll } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import {
+ buildIndex,
+ frontCode,
+ isGenerated,
+ packPosting,
+ plainText,
+ slugifyHeading,
+ splitSections,
+ tokenize,
+} from '../scripts/build-docs-search-index.mjs';
+
+const ROOT = resolve(import.meta.dirname, '..');
+
+// The runtime is a browser script that assigns itself onto the global.
+await import('../public/docs-search.js');
+const engine = globalThis.twsDocsSearch;
+
+const RUNTIME_SOURCE = readFileSync(resolve(ROOT, 'public/docs-search.js'), 'utf8');
+const BUILDER_SOURCE = readFileSync(resolve(ROOT, 'scripts/build-docs-search-index.mjs'), 'utf8');
+const DOCS_SHELL = readFileSync(resolve(ROOT, 'docs/index.html'), 'utf8');
+
+describe('docs search: builder helpers', () => {
+ it('slugifies headings the way the docs reader assigns heading ids', () => {
+ expect(slugifyHeading('Master wallet vs agent wallet')).toBe('master-wallet-vs-agent-wallet');
+ expect(slugifyHeading('Step 3 & Fund the wallet')).toBe('step-3--fund-the-wallet');
+ expect(slugifyHeading(' Trailing and leading ')).toBe('trailing-and-leading');
+ expect(slugifyHeading('')).toBe('');
+ });
+
+ it('reduces markdown to the text a reader sees', () => {
+ expect(plainText('A [link](/docs/x) and `code` and **bold**')).toBe('A link and code and bold');
+ expect(plainText('![alt](/img.png) after')).toBe('after');
+ expect(plainText('| a | b |')).toBe('a b');
+ });
+
+ it('keeps compound technical terms and also indexes their parts', () => {
+ expect(tokenize('erc-8004')).toEqual(['erc-8004', 'erc', '8004']);
+ expect(tokenize('x402 payments')).toEqual(['x402', 'payments']);
+ // Punctuation at the edges is noise; inside a token it is meaning.
+ expect(tokenize('(x402),')).toEqual(['x402']);
+ });
+
+ it('drops stopwords, single characters, and identifier noise', () => {
+ expect(tokenize('the a of')).toEqual([]);
+ expect(tokenize('x')).toEqual([]);
+ // A transaction hash and a block number: unique, unsearchable, pure bloat.
+ expect(tokenize('deadbeefcafe1234')).toEqual([]);
+ expect(tokenize('1234567')).toEqual([]);
+ // Short numbers still matter (HTTP statuses, chain ids).
+ expect(tokenize('402')).toEqual(['402']);
+ });
+
+ it('detects generated aggregates by the marker generators already write', () => {
+ expect(isGenerated('<!-- GENERATED by scripts/combine-docs.mjs -->\n# Title')).toBe(true);
+ // A generator stamps its output at the top. The same words further down are
+ // prose about generators, not a claim that this file is one.
+ expect(isGenerated('# Title\n\nProse.\n\nMore.\n\n<!-- GENERATED files look like this -->')).toBe(false);
+ expect(isGenerated('# A normal document\n\nProse.')).toBe(false);
+ });
+});
+
+describe('docs search: section splitting', () => {
+ const sample = [
+ '---',
+ 'title: front matter that must not be indexed',
+ '---',
+ '# Doc Title',
+ '',
+ 'Lead paragraph that belongs to the document rather than to any section of it.',
+ '',
+ '## First Section',
+ '',
+ 'Enough prose here to clear the minimum length that keeps stubs out of the index entirely.',
+ '',
+ '```js',
+ 'const secretIdentifierNobodySearchesFor = 1;',
+ '```',
+ '',
+ '### Nested Section',
+ '',
+ 'A third-level heading is a real destination in the reader, so it is a real section here too.',
+ '',
+ '## Stub',
+ '',
+ 'Too short.',
+ ].join('\n');
+
+ const parsed = splitSections(sample, 'fallback');
+
+ it('takes the document title from the H1 without making it a section', () => {
+ expect(parsed.title).toBe('Doc Title');
+ expect(parsed.sections.map((s) => s.heading)).toEqual(['', 'First Section', 'Nested Section']);
+ });
+
+ it('keeps the lead paragraph as the untitled opening section', () => {
+ expect(parsed.sections[0].text).toContain('Lead paragraph');
+ expect(parsed.sections[0].text).not.toContain('front matter');
+ });
+
+ it('never indexes code fences', () => {
+ const all = parsed.sections.map((s) => s.text).join(' ');
+ expect(all).not.toContain('secretIdentifierNobodySearchesFor');
+ });
+
+ it('drops sections too short to answer anything', () => {
+ expect(parsed.sections.some((s) => s.heading === 'Stub')).toBe(false);
+ });
+
+ it('falls back to a supplied title when the file has no H1', () => {
+ expect(splitSections('Body prose long enough to survive the minimum section length filter.', 'my doc').title).toBe(
+ 'my doc',
+ );
+ });
+});
+
+describe('docs search: encoding round-trips', () => {
+ it('front codes and expands a sorted vocabulary losslessly', () => {
+ const terms = ['agent', 'agents', 'agentwallet', 'wallet', 'x402'];
+ expect(engine.expandTerms(frontCode(terms))).toEqual(terms);
+ });
+
+ it('front coding survives a shared prefix longer than one base-36 digit', () => {
+ const long = 'a'.repeat(40);
+ const terms = [long, `${long}b`];
+ expect(engine.expandTerms(frontCode(terms))).toEqual(terms);
+ });
+
+ it('packs a section gap and a term frequency into one integer', () => {
+ expect(packPosting(0, 1) % 16).toBe(1);
+ expect(Math.floor(packPosting(7, 3) / 16)).toBe(7);
+ // Frequencies above the 4-bit ceiling clamp rather than overflow into the
+ // gap, which would move the posting to a different section entirely.
+ expect(packPosting(2, 99) % 16).toBe(15);
+ expect(Math.floor(packPosting(2, 99) / 16)).toBe(2);
+ });
+});
+
+describe('docs search: builder and runtime agree', () => {
+ it('tokenizes identically on both sides', () => {
+ const samples = [
+ 'How do I fund an agent wallet?',
+ 'erc-8004 identity',
+ 'x402 / MCP tools',
+ 'Next.js embed',
+ 'THE END',
+ '0xdeadbeefcafe',
+ 'viseme_aa lip-sync',
+ ];
+ for (const sample of samples) {
+ expect(engine.tokenize(sample), sample).toEqual(tokenize(sample));
+ }
+ });
+
+ it('shares one stopword list', () => {
+ const list = (source) => source.match(/\('(a an and[\s\S]*?your)'/)[1].replace(/'\s*\+\s*'/g, '');
+ expect(list(RUNTIME_SOURCE)).toBe(list(BUILDER_SOURCE));
+ });
+
+ it('slugifies headings the same way the docs reader does', () => {
+ // All three copies of these rules must match or emitted anchors stop
+ // resolving. Compared as normalized source, so a rewritten rule fails here.
+ const body = (source) =>
+ source
+ .match(/slugifyHeading\((?:text)\)\s*\{([\s\S]*?)\n\t*\}/)[1]
+ .replace(/\s+/g, ' ')
+ .trim();
+ expect(body(RUNTIME_SOURCE)).toBe(body(BUILDER_SOURCE));
+ expect(body(DOCS_SHELL)).toBe(body(BUILDER_SOURCE));
+ });
+});
+
+describe('docs search: the real corpus', () => {
+ let index;
+ let sourceOf;
+
+ beforeAll(() => {
+ index = buildIndex();
+ engine.load(index);
+ sourceOf = new Map();
+ });
+
+ it('indexes the documentation and skips generated aggregates', () => {
+ expect(index.docCount).toBeGreaterThan(200);
+ expect(index.sectionCount).toBeGreaterThan(1000);
+ expect(index.skippedGenerated).toContain('ALL');
+ expect(index.docs.some(([slug]) => slug === 'ALL')).toBe(false);
+ });
+
+ it('emits anchors that exist as headings in the document they point at', () => {
+ // Sample across the corpus rather than all 6,000 sections: this reads
+ // every sampled file from disk.
+ const step = Math.floor(index.sectionCount / 60) || 1;
+ for (let i = 0; i < index.sectionCount; i += step) {
+ const [docId, heading] = index.sections[i];
+ if (!heading) continue;
+ const slug = index.docs[docId][0];
+ if (!sourceOf.has(slug)) sourceOf.set(slug, readFileSync(resolve(ROOT, 'docs', `${slug}.md`), 'utf8'));
+ const anchor = slugifyHeading(heading);
+ const headings = sourceOf
+ .get(slug)
+ .split(/\r?\n/)
+ .filter((line) => /^#{1,3}\s/.test(line))
+ .map((line) => slugifyHeading(plainText(line.replace(/^#{1,3}\s+/, ''))));
+ expect(headings, `${slug} → ${anchor}`).toContain(anchor);
+ }
+ });
+
+ it('routes every result through the docs reader hash format', () => {
+ for (const hit of engine.query('agent wallet', 8)) {
+ expect(hit.url).toMatch(/^\/docs#[\w./-]+(@[\w-]*)?$/);
+ expect(hit.docTitle).toBeTruthy();
+ }
+ });
+
+ it('finds a section from its own heading', () => {
+ // Self-retrieval: the strongest relevance assertion that does not encode
+ // today's corpus into the test. A heading distinctive enough to be worth
+ // linking should retrieve its own section.
+ const candidates = [];
+ const step = Math.floor(index.sectionCount / 80) || 1;
+ for (let i = 0; i < index.sectionCount; i += step) {
+ const heading = index.sections[i][1];
+ if (heading && tokenize(heading).length >= 3) candidates.push(i);
+ }
+ expect(candidates.length).toBeGreaterThan(20);
+
+ let found = 0;
+ for (const sectionId of candidates) {
+ const [docId, heading] = index.sections[sectionId];
+ const slug = index.docs[docId][0];
+ const anchor = slugifyHeading(heading);
+ const hits = engine.query(heading, 5);
+ if (hits.some((h) => h.slug === slug && h.anchor === anchor)) found++;
+ }
+ // Not 100%: long-form docs are also published split into chapters, and the
+ // duplicate-heading suppression deliberately keeps only one of the copies.
+ expect(found / candidates.length).toBeGreaterThan(0.8);
+ });
+
+ it('returns nothing rather than everything for an unknown term', () => {
+ expect(engine.query('zzzzqqqxnotaword')).toEqual([]);
+ expect(engine.query('')).toEqual([]);
+ expect(engine.query(' ')).toEqual([]);
+ });
+
+ it('never returns more sections from one document than the cap allows', () => {
+ const perDoc = {};
+ for (const hit of engine.query('agent', 8)) perDoc[hit.slug] = (perDoc[hit.slug] || 0) + 1;
+ for (const slug of Object.keys(perDoc)) expect(perDoc[slug]).toBeLessThanOrEqual(2);
+ });
+
+ it('is deterministic, so --check can trust a byte comparison', () => {
+ expect(JSON.stringify(buildIndex())).toBe(JSON.stringify(index));
+ });
+});