Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
feat(docs): separate Python and Rust pages under /docs and /docs/rust (#2742)
LJ π₯₯π΄7b2f5d4f402d
diff --git a/docs/CONTENT_LANGUAGES.md b/docs/CONTENT_LANGUAGES.mdnew file mode 100644index 00000000..e5cbb56c--- /dev/null+++ b/docs/CONTENT_LANGUAGES.md@@ -0,0 +1,129 @@+# Python and Rust pages++The docs have one tree per SDK language, built from the same source files:++| Language | URL | Example |+|---|---|---|+| Python | `/docs/<slug>/` | `/docs/programming_guide/function/` |+| Rust | `/docs/rust/<slug>/` | `/docs/rust/programming_guide/function/` |++Each page shows one language. A switch at the top of the sidebar moves between+the two copies of a page, the sidebar lists only the current language's pages,+and the breadcrumb shows a "Python SDK" or "Rust SDK" badge. The machinery is+in `src/lib/lang.ts`; this file is the authoring contract.++## Frontmatter++| Key | Meaning |+|---|---|+| `languages: [python, rust]` | The trees the page is in. Absent means both. Use `[python]` for a Python-only page (for example `ops/litellm`) and `[rust]` for a Rust-only page. |+| `rust_title`, `rust_description` | Title and lede on the Rust page, when they differ from `title` / `description`. Same `*accent*` markup as `title`. Quote a value that contains ` #` (YAML reads it as a comment): `rust_title: "Declaring *functions* with #[cocoindex::function]"`. |+| `route: <slug>` | The page's slug in its trees, when it is not the file path. A Rust-only file can take the slot of a Python page this way: `getting_started/rust_quickstart.mdx` has `languages: [rust]` and `route: getting_started/quickstart`, so it is `/docs/rust/getting_started/quickstart/`. |+| `python_counterpart: <slug>`, `rust_counterpart: <slug>` | Where the language switch goes from a one-language page (for example `rust_counterpart: ops/model_apis` on `ops/litellm`). Without it the switch goes to the page in the same slot, else the section index, else the tree's root. |+| `neutral: true` | The page reads the same in both languages (FAQ, About, Contributing). The Rust copy's canonical URL is the Python one, so search engines see one page. |++## Components++These need no `import` in a page.++### `<LangTabs>`: a Python / Rust pair++Renders only the slot of the page's language, with no tab UI. Keep the two+samples side by side in the source:++````mdx+<LangTabs>+<Fragment slot="python">++```python+async def process_file(file: FileLike) -> str:+ return await file.read_text()+```++</Fragment>+<Fragment slot="rust">++```rust+#[cocoindex::function]+async fn process_file(_ctx: &Ctx, file: FileEntry) -> Result<String> {+ Ok(file.content_str()?.to_string())+}+```++</Fragment>+</LangTabs>+````++A code block outside `LangTabs` and outside `Lang` shows on both pages. On a+page in both trees, put every language-specific code block in one of them.++### `<Lang only="python">` / `<Lang only="rust">`: prose for one language++Inline:++```mdx+Mark the function <Lang only="python">`@coco.fn`</Lang><Lang only="rust">`#[cocoindex::function]`</Lang> to memoize it.+```++Around blocks (blank lines inside the tags), including headings, lists and+code. A heading inside appears only in that language's table of contents:++```mdx+<Lang only="python">++## Async adapter++`@coco.fn` keeps the sync or async nature of the function.++</Lang>+```++Do not nest `Lang` in `Lang`.++### `<RustNote>`: a difference from Python++Shown on Rust pages only, as a callout titled "Different from Python". Use it+where the Rust SDK differs on purpose, at the point it matters:++```mdx+<RustNote>+The Rust SDK has no sync/async adapter: a `#[cocoindex::function]` body is an+`async fn`, and every function takes the component's `&Ctx` first.+</RustNote>+```++`<RustNote title="β¦">` changes the label.++## Links++- A **source-relative** link (`./app`, `../connectors/postgres`) opens the+ linked file's page in the reader's language when the page has one, else in+ the language it has. Write these by default.+- A **root-relative** link (`/docs/cli/`, `/docs/rust/cli/`) is taken as+ written. Use it to point at one language on purpose, for example "see the+ [Python CLI](/docs/cli/)" on a Rust page.++## Agent-facing files++Each language has its own `.md` twins (`/docs/<slug>.md`,+`/docs/rust/<slug>.md`), `llms.txt` and `llms-full.txt`. The twins keep only+the page's language: `Lang`, `LangTabs` slots and `RustNote` of the other+language are dropped. `scripts/check-agent-output.mjs` checks that every page+has a twin per language and that every code block appears in one of them.++## Reference page++`programming_guide/function.mdx` uses each piece: `rust_title`, `rust_description`, inline `Lang`, a block `Lang` heading pair, a `RustNote`, and `LangTabs`.++## Checklist for a page++1. Set `languages` if the page is not in both trees.+2. Set `rust_title` / `rust_description` if the title or lede names a Python API.+3. Put every Python-only and Rust-only code block in `LangTabs` or `Lang`.+4. Wrap prose that names one language's API (`@coco.fn`, `coco.mount`,+ `asyncpg.Pool`, `#[cocoindex::function]`, `Ctx`) in `Lang`, or reword it+ so it holds for both.+5. Replace "the Rust SDK β¦" asides on shared prose with `RustNote` or a+ `Lang only="rust"` block.+6. Build (`npm run build`) and read both copies of the page.diff --git a/docs/scripts/check-agent-output.mjs b/docs/scripts/check-agent-output.mjsindex 01a5b71b..2b2a5930 100644--- a/docs/scripts/check-agent-output.mjs+++ b/docs/scripts/check-agent-output.mjs@@ -30,7 +30,7 @@ const contentFiles = (dir) => walk(dir, /\.mdx?$/);const read = (p) => readFileSync(p, 'utf8');// 1. Required artifacts exist; hosted references match the skill folder.-for (const f of ['llms.txt', 'llms-full.txt', 'skill.md']) {+for (const f of ['llms.txt', 'llms-full.txt', 'rust/llms.txt', 'rust/llms-full.txt', 'skill.md']) {if (!existsSync(join(DIST, f))) errors.push(`missing dist/${f}`);}const refNames = readdirSync(REFERENCES_DIR)@@ -51,12 +51,30 @@ for (const name of refNames) {}// 2. Every content page has its .md twin: docs pages and example walkthroughs.+// A docs page has one twin per SDK language it lists (frontmatter+// `languages`, default both): /<route>.md for Python, /rust/<route>.md for+// Rust, where `route` defaults to the file's slug (src/lib/lang.ts).const docSlug = (src) =>relative(DOCS_SRC, src).replace(/\.mdx?$/, '').replace(/\/index$/, '');const postSlug = (src) => relative(POSTS_SRC, src).replace(/\.mdx?$/, '');+const frontmatter = (src) => {+ const m = /^---\n([\s\S]*?)\n---\n/.exec(read(src).replace(/\r\n/g, '\n'));+ return m ? m[1] : '';+};+const docTwins = (src) => {+ const fm = frontmatter(src);+ const langs = /^languages:\s*\[([^\]]*)\]/m.exec(fm)?.[1]+ .split(',')+ .map((l) => l.trim())+ .filter(Boolean) ?? ['python', 'rust'];+ const route = /^route:\s*(\S+)/m.exec(fm)?.[1].replace(/^\/+|\/+$/g, '') ?? docSlug(src);+ return langs.map((l) => (l === 'python' ? `${route}.md` : `${l}/${route}.md`));+};for (const src of contentFiles(DOCS_SRC)) {- if (!existsSync(join(DIST, `${docSlug(src)}.md`)))- errors.push(`missing .md twin for docs page: ${docSlug(src)}`);+ for (const twin of docTwins(src)) {+ if (!existsSync(join(DIST, twin)))+ errors.push(`missing .md twin for docs page ${docSlug(src)}: ${twin}`);+ }}for (const src of contentFiles(POSTS_SRC)) {const slug = postSlug(src);@@ -103,18 +121,21 @@ const survivingFences = (body) => {for (const m of s.matchAll(/\x00F(\d+)\x00/g)) out.push(fences[Number(m[1])]);return out;};-const checkFences = (srcPath, outPath, label) => {- const out = agentFiles.get(outPath);- if (out === undefined) return;+// A docs page's fence belongs to one SDK language or both, so each fence+// must appear in at least one of the page's language twins.+const checkFences = (srcPath, outPaths, label) => {+ const outs = outPaths.map((p) => agentFiles.get(p)).filter((o) => o !== undefined);+ if (!outs.length) return;for (const fence of survivingFences(read(srcPath).replace(/\r\n/g, '\n'))) {- if (!out.includes(fence)) errors.push(`fenced block corrupted in ${label}`);+ if (!outs.some((out) => out.includes(fence))) errors.push(`fenced block corrupted in ${label}`);}};for (const src of contentFiles(DOCS_SRC)) {- checkFences(src, join(DIST, `${docSlug(src)}.md`), `${docSlug(src)}.md`);+ const twins = docTwins(src);+ checkFences(src, twins.map((t) => join(DIST, t)), twins.join(' / '));}for (const src of contentFiles(POSTS_SRC)) {- checkFences(src, join(DIST, 'examples', `${postSlug(src)}.md`), `examples/${postSlug(src)}.md`);+ checkFences(src, [join(DIST, 'examples', `${postSlug(src)}.md`)], `examples/${postSlug(src)}.md`);}// 5. Each example's .env.example is a superset of its tracked .env β thediff --git a/docs/scripts/remark-link-checker.mjs b/docs/scripts/remark-link-checker.mjsindex 737dc883..e566ebc2 100644--- a/docs/scripts/remark-link-checker.mjs+++ b/docs/scripts/remark-link-checker.mjs@@ -253,6 +253,11 @@ export default function remarkLinkChecker(options = {}) {const joined = posix.join('/', base.replace(/^\//, ''), slug);const absPath = joined.endsWith('/') ? joined : `${joined}/`;node.url = fragment ? `${absPath}#${fragment}` : absPath;+ // Mark it as a page link so LangLink (src/components/LangLink.astro)+ // points it into the reader's SDK language tree (/docs/rust/<slug>/+ // on a Rust page). Root-relative links an author writes stay exact.+ node.data = node.data ?? {};+ node.data.hProperties = { ...(node.data.hProperties ?? {}), 'data-doc-link': slug };}});diff --git a/docs/src/components/Lang.astro b/docs/src/components/Lang.astronew file mode 100644index 00000000..5e84bbe8--- /dev/null+++ b/docs/src/components/Lang.astro@@ -0,0 +1,17 @@+---+// Content for one SDK language: renders its children only on that language's+// page (/docs/<slug>/ is Python, /docs/rust/<slug>/ is Rust). Works inline+// ("decorate it with <Lang only="python">`@coco.fn`</Lang><Lang+// only="rust">`#[cocoindex::function]`</Lang>") and around blocks (put blank+// lines inside the tags). Headings inside stay out of the other language's+// table of contents and its raw-Markdown twin. Do not nest Lang in Lang.+// Authoring contract: docs/CONTENT_LANGUAGES.md.+import { currentLang, type Lang } from '../lib/lang';++interface Props {+ only: Lang;+}+const { only } = Astro.props;+const show = currentLang(Astro) === only;+---+{show && <slot />}diff --git a/docs/src/components/LangLink.astro b/docs/src/components/LangLink.astronew file mode 100644index 00000000..f6f5fa8e--- /dev/null+++ b/docs/src/components/LangLink.astro@@ -0,0 +1,23 @@+---+// Every Markdown link in a docs page renders through this (see+// src/pages/[...slug].astro `components={{ a: LangLink }}`). A source-relative+// link to another docs page (`./app`, `../connectors/postgres`), which+// remark-link-checker marks with `data-doc-link`, points into the reader's+// language tree (/docs/rust/<slug>/ on a Rust page) when the target has a page+// there, else to the target's counterpart, else to the page in the language it+// exists in. Root-relative links (`/docs/cli/`) are taken as written: use them+// to point at one language on purpose.+import type { HTMLAttributes } from 'astro/types';+import { DOCS_BASE } from '../consts';+import { currentLang, pageRegistry } from '../lib/lang';++type Props = HTMLAttributes<'a'> & { 'data-doc-link'?: string };+const { href, 'data-doc-link': docLink, ...rest } = Astro.props;+let out = typeof href === 'string' ? href : href?.toString();+if (docLink && out?.startsWith(`${DOCS_BASE}/`)) {+ const hash = out.split('#')[1];+ const hit = (await pageRegistry()).resolve(docLink, currentLang(Astro));+ if (hit) out = hit.href + (hash ? `#${hash}` : '');+}+---+<a href={out} {...rest}><slot /></a>diff --git a/docs/src/components/LangSwitch.astro b/docs/src/components/LangSwitch.astronew file mode 100644index 00000000..31e0af0a--- /dev/null+++ b/docs/src/components/LangSwitch.astro@@ -0,0 +1,83 @@+---+// Python | Rust switch at the top of the sidebar (and in the mobile sheet).+// Each side is a plain link to the same page in that language's tree+// (/docs/<slug>/ β /docs/rust/<slug>/), or to its counterpart, section index+// or tree root when the page has no copy there. The click also stores the+// choice for the docs home; nothing redirects on its own, so a shared link+// always opens the language in its path.+import { LANGS, LANG_LABEL, pageRegistry, type Lang } from '../lib/lang';++interface Props {+ lang: Lang;+ /** Route of the current page; '' for a tree's root. */+ route: string;+}+const { lang, route } = Astro.props;+const reg = await pageRegistry();+const links = LANGS.map((l) => ({+ lang: l,+ label: LANG_LABEL[l],+ href: l === lang ? undefined : reg.switchTarget(lang, route, l),+}));+---++<nav class="lang-switch" aria-label="SDK language">+ {links.map((l) =>+ l.href ? (+ <a class="lang-opt" href={l.href} data-lang-choice={l.lang} hreflang="en">+ <span class={`lang-dot ${l.lang}`} aria-hidden="true"></span>{l.label}+ </a>+ ) : (+ <span class="lang-opt on" aria-current="true">+ <span class={`lang-dot ${l.lang}`} aria-hidden="true"></span>{l.label}+ </span>+ ),+ )}+</nav>++<script>+ for (const a of document.querySelectorAll<HTMLAnchorElement>('[data-lang-choice]')) {+ a.addEventListener('click', () => {+ try {+ localStorage.setItem('coco-docs-lang', a.dataset.langChoice ?? '');+ } catch {+ // Private mode or a full store: the link still navigates.+ }+ });+ }+</script>++<style>+ .lang-switch {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 2px;+ padding: 3px;+ margin: 0 0 10px;+ background: #141414;+ border: 1px solid var(--rule);+ border-radius: var(--r-md, 9px);+ }+ .lang-opt {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 7px;+ padding: 6px 0;+ font-family: var(--sans);+ font-size: 0.8125rem;+ line-height: 1.2;+ color: var(--muted);+ text-decoration: none;+ border-radius: var(--r-sm, 6px);+ }+ a.lang-opt:hover { color: var(--text); background: rgba(255, 255, 255, 0.04); }+ .lang-opt.on {+ color: var(--text);+ background: #262626;+ box-shadow: inset 0 0 0 1px var(--rule-strong);+ }+ .lang-dot { width: 7px; height: 7px; border-radius: 50%; flex: none; }+ .lang-dot.python { background: var(--lang-python, #4b8bbe); }+ .lang-dot.rust { background: var(--lang-rust, #e8743d); }+</style>diff --git a/docs/src/components/LangTabs.astro b/docs/src/components/LangTabs.astroindex 1a678144..36d13047 100644--- a/docs/src/components/LangTabs.astro+++ b/docs/src/components/LangTabs.astro@@ -1,8 +1,8 @@----// A Python / Rust tab pair whose selection is shared by every LangTabs on the-// page and remembered across pages (localStorage), so a reader picks a-// language once. Markup and styling come from Tabs.astro; this adds the-// slot names and the sync script.+// A Python / Rust pair of code samples (or any content). Each page shows one+// language, so this renders only the slot of the page's language, with no tab+// UI: Python pages show `python`, Rust pages show `rust`. Kept as a pair so the+// two samples stay side by side in the source.//// <LangTabs>// <Fragment slot="python">@@ -12,50 +12,14 @@// ```rust ... ```// </Fragment>// </LangTabs>-import Tabs from './Tabs.astro';+//+// Authoring contract: docs/CONTENT_LANGUAGES.md.+import { currentLang } from '../lib/lang';+interface Props {- /** Index of the tab selected on load: 0 for Python, 1 for Rust. */+ /** Ignored: kept so pages written for the tabbed form still build. */initial?: number;}-const { initial = 0 } = Astro.props;+const lang = currentLang(Astro);----<div class="coco-lang-tabs" data-lang-tabs>- <Tabs labels={['Python', 'Rust']} initial={initial} label="Language">- <Fragment slot="tab-0"><slot name="python" /></Fragment>- <Fragment slot="tab-1"><slot name="rust" /></Fragment>- </Tabs>-</div>--<script>- // Astro bundles this once per page. All groups follow one selection, stored- // under `coco-docs-lang`; the clicked label keeps its place on screen so a- // switch that resizes groups above it does not jump the page.- const STORAGE_KEY = 'coco-docs-lang';- const groups = Array.from(document.querySelectorAll<HTMLElement>('[data-lang-tabs]'));- const radiosOf = (group: HTMLElement) =>- Array.from(group.querySelectorAll<HTMLInputElement>(':scope > .coco-tabs > .coco-tabs-radio'));- const select = (index: number) => {- for (const group of groups) {- const radio = radiosOf(group)[index];- if (radio && !radio.checked) radio.checked = true;- }- };- const stored = Number(localStorage.getItem(STORAGE_KEY));- if (Number.isInteger(stored) && stored >= 0) select(stored);- for (const group of groups) {- group.addEventListener('change', (event) => {- const radio = event.target;- if (!(radio instanceof HTMLInputElement)) return;- const index = radiosOf(group).indexOf(radio);- if (index < 0) return;- const before = group.getBoundingClientRect().top;- select(index);- window.scrollBy(0, group.getBoundingClientRect().top - before);- try {- localStorage.setItem(STORAGE_KEY, String(index));- } catch {- // Private mode or a full store: the page-level sync still applies.- }- });- }-</script>+{lang === 'rust' ? <slot name="rust" /> : <slot name="python" />}diff --git a/docs/src/components/MobileSheet.astro b/docs/src/components/MobileSheet.astroindex 46ea8d4a..f6e1c64d 100644--- a/docs/src/components/MobileSheet.astro+++ b/docs/src/components/MobileSheet.astro@@ -12,6 +12,8 @@ import type { MarkdownHeading } from 'astro';import { sidebar, type SidebarItem } from '../data/docs-sidebar';import { SITE_MAIN, SITE_BLOG, SITE_EXAMPLES } from '../consts';import Search from './Search.astro';+import LangSwitch from './LangSwitch.astro';+import { langHref, type Lang } from '../lib/lang';import MobileSheet from '@cocoindex/brand/MobileSheet.astro';export interface Props {@@ -23,12 +25,16 @@ export interface Props {* `null` to render no docs sidebar (e.g. on examples listing or 404).* Defaults to the docs-sidebar tree (regular doc pages). */sidebarItems?: SidebarItem[] | null;+ /** SDK language of a docs page: shows the Python | Rust switch and links+ * into that language's tree. Absent on non-docs pages. */+ lang?: Lang;}const {currentSlug = '',headings = [],sidebarItems: sidebarItemsRaw,+ lang,} = Astro.props;const sidebarItems: SidebarItem[] | null =sidebarItemsRaw === undefined ? sidebar : sidebarItemsRaw;@@ -61,11 +67,13 @@ const tocRows = headings.filter((h) => h.depth >= 2 && h.depth <= 4);function href(slug: string): string {// Trailing slash matches the canonical URL Astro emits under// `build.format: 'directory'` β saves a 301 round-trip per click.- return `${base}/${slug}/`;+ if (lang) return langHref(lang, slug);+ return slug ? `${base}/${slug}/` : `${base}/`;}---<MobileSheet id="mobileSheet" title="Menu" closeAbove={1120}>+ {lang && <LangSwitch lang={lang} route={currentSlug} />}<div class="mobile-search"><Search /></div>@@ -98,10 +106,10 @@ function href(slug: string): string {)}<div class="mobile-pane" id="panePages" role={tocRows.length > 0 ? 'tabpanel' : undefined} aria-labelledby={tocRows.length > 0 ? 'tabPages' : undefined}>- {sidebarItems === sidebar && (+ {(sidebarItems === sidebar || lang) && (<div class="mobile-group"><nav class="mobile-list" aria-label="Documentation home">- <a href={`${base}/`} aria-current={currentSlug === '' ? 'page' : undefined}>+ <a href={href('')} aria-current={currentSlug === '' ? 'page' : undefined}><span class="lbl">About CocoIndex</span></a></nav>diff --git a/docs/src/components/RustNote.astro b/docs/src/components/RustNote.astronew file mode 100644index 00000000..a7a8c741--- /dev/null+++ b/docs/src/components/RustNote.astro@@ -0,0 +1,33 @@+---+// "Different from Python" callout, shown on Rust pages only. Use it where the+// Rust SDK behaves differently from the Python SDK on purpose, so a reader+// coming from Python sees the difference at the point it matters. Styled as a+// site callout (src/styles/site.css .callout) with the Rust accent.+// Authoring contract: docs/CONTENT_LANGUAGES.md.+import { currentLang } from '../lib/lang';++interface Props {+ /** Label shown in bold; defaults to "Different from Python". */+ title?: string;+}+const { title = 'Different from Python' } = Astro.props;+const show = currentLang(Astro) === 'rust';+---+{show && (+ <div class="callout lang-diff">+ <div class="ico" aria-hidden="true">+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 5h9M8 2l3 3-3 3"/><path d="M14 11H5M8 8l-3 3 3 3"/></svg>+ </div>+ <div class="body"><b class="callout-label">{title}</b><slot /></div>+ </div>+)}++<style>+ /* The site callout, with a left rule in the Rust accent. */+ .lang-diff {+ border-left: 3px solid var(--lang-rust, #e8743d);+ padding-left: 13px;+ }+ .lang-diff .ico { color: var(--lang-rust, #e8743d); }+ .lang-diff .callout-label { color: var(--lang-rust, #e8743d); }+</style>diff --git a/docs/src/components/Search.astro b/docs/src/components/Search.astroindex fb1c0b3c..6c27da79 100644--- a/docs/src/components/Search.astro+++ b/docs/src/components/Search.astro@@ -129,6 +129,16 @@ const available = !!APP_ID && !!API_KEY;indexName: cfg.INDEX,container: host,hitComponent: accessibleSearchHit,+ // One SDK language per tree: a page in /docs/rust/ searches the+ // Rust pages, any other page the Python ones. The language comes+ // from <html data-docs-lang> (DocsLayout). Until the crawler has+ // indexed /docs/rust/, a Rust search falls back to all hits.+ transformItems: (items) => {+ const rust = document.documentElement.dataset.docsLang === 'rust';+ const inRust = (url: string) => /\/docs\/rust\//.test(url);+ const mine = items.filter((it) => inRust(it.url) === rust);+ return rust && mine.length === 0 ? items : mine;+ },});installSearchAccessibility(host, () => {const target = returnTo;diff --git a/docs/src/components/Sidebar.astro b/docs/src/components/Sidebar.astroindex cbdaa8d9..a045708a 100644--- a/docs/src/components/Sidebar.astro+++ b/docs/src/components/Sidebar.astro@@ -1,29 +1,32 @@----import { sidebar, type SidebarItem } from '../data/docs-sidebar';+import { sidebar } from '../data/docs-sidebar';+import { langHref, pageRegistry, sidebarFor, type Lang } from '../lib/lang';+import LangSwitch from './LangSwitch.astro';import Search from './Search.astro';export interface Props {- /** Slug of the currently-rendered doc, e.g. `getting_started/quickstart`. */+ /** Route of the currently-rendered doc, e.g. `getting_started/quickstart`. */currentSlug: string;+ /** SDK language of the page: the sidebar lists that language's pages. */+ lang: Lang;}-const { currentSlug } = Astro.props;-const base = import.meta.env.BASE_URL.replace(/\/$/, '');+const { currentSlug, lang } = Astro.props;+const items = sidebarFor(sidebar, lang, await pageRegistry());-function href(slug: string): string {- // Trailing slash matches the canonical URL Astro emits under- // `build.format: 'directory'` β saves a 301 round-trip per click.- return `${base}/${slug}/`;-}+// Trailing slash matches the canonical URL Astro emits under+// `build.format: 'directory'` β saves a 301 round-trip per click.+const href = (slug: string): string => langHref(lang, slug);---<aside class="side" aria-label="Documentation pages">+ <LangSwitch lang={lang} route={currentSlug} /><Search /><div class="side-group"><ul><li><a- href={`${base}/`}+ href={href('')}class={currentSlug === '' ? 'on' : ''}data-current={currentSlug === '' || null}aria-current={currentSlug === '' ? 'page' : undefined}@@ -33,7 +36,7 @@ function href(slug: string): string {</li></ul></div>- {sidebar.map((item) => (+ {items.map((item) => (item.type === 'doc' ? (<div class="side-group"><ul>diff --git a/docs/src/content/docs/about/community.mdx b/docs/src/content/docs/about/community.mdxindex 2b504119..921e70de 100644--- a/docs/src/content/docs/about/community.mdx+++ b/docs/src/content/docs/about/community.mdx@@ -3,6 +3,8 @@ title: Join the *community*description: >Find the Discord, GitHub, Twitter, LinkedIn, and YouTube channels where theCocoIndex community asks questions, shares ideas, and gets support.+# Reads the same in both SDK languages (src/lib/lang.ts).+neutral: true---Contribute code, update documentation, or report bugs and feature requests on [GitHub](https://github.com/cocoindex-io/cocoindex).Use the [Contributing guide](../contributing/guide) to set up your development environment.diff --git a/docs/src/content/docs/about/telemetry.mdx b/docs/src/content/docs/about/telemetry.mdxindex bc1bdc04..1d60101c 100644--- a/docs/src/content/docs/about/telemetry.mdx+++ b/docs/src/content/docs/about/telemetry.mdx@@ -3,6 +3,8 @@ title: Anonymous *usage telemetry*description: >What CocoIndex's anonymous usage tracking collects, what it doesn't, and howto opt out.+# Reads the same in both SDK languages (src/lib/lang.ts).+neutral: true---CocoIndex sends a small number of anonymous events to help us understand howdiff --git a/docs/src/content/docs/cli.mdx b/docs/src/content/docs/cli.mdxindex 08ff7791..025f9a5a 100644--- a/docs/src/content/docs/cli.mdx+++ b/docs/src/content/docs/cli.mdx@@ -4,10 +4,11 @@ description: >Reference for the `cocoindex` CLI β app target formats, environment variableloading, and subcommands for init, ls, show, update (catch-up or live), anddrop.+languages: [python]---CocoIndex CLI is a standalone tool for managing and inspecting your apps.-This page describes the CLI for Python projects. A Rust project has its own `cocoindex` binary with the same subcommands; see [The CLI for Rust projects](./cli_rust). Both read the same state database format, so `show --db PATH --app-name NAME` works on either tool against an app the other SDK wrote.+This page describes the CLI for Python projects. A Rust project has its own `cocoindex` binary with the same subcommands; see [the Rust CLI reference](/docs/rust/cli/). Both read the same state database format, so `show --db PATH --app-name NAME` works on either tool against an app the other SDK wrote.## Invoke the CLIdiff --git a/docs/src/content/docs/cli_rust.mdx b/docs/src/content/docs/cli_rust.mdxindex ef1ddba0..41407ef1 100644--- a/docs/src/content/docs/cli_rust.mdx+++ b/docs/src/content/docs/cli_rust.mdx@@ -1,11 +1,14 @@----title: The *CLI* for Rust projects+title: The *CLI* referencedescription: >Reference for the `cocoindex` CLI for Rust projects β how it builds and drivesyour crate, the app target format, the three attributes an app registers with,and the ls, show, update, drop and init subcommands.+languages: [rust]+# The Rust page in the CLI slot: /docs/rust/cli/.+route: cli----The `cocoindex` CLI for Rust projects gives a Rust pipeline the same commands the [Python CLI](./cli) has: `ls`, `show`, `update`, `drop`, `init` and `google-drive`. The Python prose on that page describes the Python tool; this page describes the Rust tool, which is a separate binary built from the `rust/cli` crate of the repository.+The `cocoindex` CLI for Rust projects gives a Rust pipeline the same commands the [Python CLI](/docs/cli/) has: `ls`, `show`, `update`, `drop`, `init` and `google-drive`. The Python prose on that page describes the Python tool; this page describes the Rust tool, which is a separate binary built from the `rust/cli` crate of the repository.## How it worksdiff --git a/docs/src/content/docs/contributing/guide.mdx b/docs/src/content/docs/contributing/guide.mdxindex cc8c0fa8..6b810678 100644--- a/docs/src/content/docs/contributing/guide.mdx+++ b/docs/src/content/docs/contributing/guide.mdx@@ -6,6 +6,8 @@ description: >workflow.meta:time: ~15 minutes+# Reads the same in both SDK languages (src/lib/lang.ts).+neutral: true---[CocoIndex](https://github.com/cocoindex-io/cocoindex) is an open source project. Contributions can include code, documentation, bug reports, and feature requests.diff --git a/docs/src/content/docs/contributing/setup_dev_environment.mdx b/docs/src/content/docs/contributing/setup_dev_environment.mdxindex 4c66d880..e23a20cb 100644--- a/docs/src/content/docs/contributing/setup_dev_environment.mdx+++ b/docs/src/content/docs/contributing/setup_dev_environment.mdx@@ -6,6 +6,8 @@ description: >meta:time: ~15 minutesrequires: Rust + uv+# Reads the same in both SDK languages (src/lib/lang.ts).+neutral: true---Follow the steps below to get CocoIndex built on the latest codebase locally - if you are making changes to CocoIndex functionality and want to test it out.diff --git a/docs/src/content/docs/faq.mdx b/docs/src/content/docs/faq.mdxindex e6720920..e14dd514 100644--- a/docs/src/content/docs/faq.mdx+++ b/docs/src/content/docs/faq.mdx@@ -4,6 +4,8 @@ description: >Common questions about CocoIndex behavior β how change detection propagatesthrough logic vs inputs, runtime invocation tracking, hidden dependencies,and crash recovery vs cross-target atomicity for target states.+# Reads the same in both SDK languages (src/lib/lang.ts).+neutral: true---## Change detectiondiff --git a/docs/src/content/docs/getting_started/quickstart.mdx b/docs/src/content/docs/getting_started/quickstart.mdxindex 07977f81..7f4c1348 100644--- a/docs/src/content/docs/getting_started/quickstart.mdx+++ b/docs/src/content/docs/getting_started/quickstart.mdx@@ -3,6 +3,7 @@ title: CocoIndex *quickstart*description: >Build your first CocoIndex pipeline: convert PDFs to Markdownand watch incremental processing only reprocess files that actually changed.+languages: [python]---import AppExample from '/src/components/diagrams/concepts/AppExample.astro';import FileProcess from '/src/components/diagrams/concepts/FileProcess.astro';diff --git a/docs/src/content/docs/getting_started/rust_quickstart.mdx b/docs/src/content/docs/getting_started/rust_quickstart.mdxindex 1d6631c0..2d4f58e4 100644--- a/docs/src/content/docs/getting_started/rust_quickstart.mdx+++ b/docs/src/content/docs/getting_started/rust_quickstart.mdx@@ -1,11 +1,14 @@----title: Rust SDK quickstart+title: CocoIndex *quickstart*description: >Build an incremental Rust pipeline that chunks Markdown, batches and cacheslocal embeddings, and keeps a Postgres/pgvector table in sync.meta:language: Rust 1.89+requires: Postgres with pgvector+languages: [rust]+# The Rust page in the quickstart slot: /docs/rust/getting_started/quickstart/.+route: getting_started/quickstart---Build the Rust version of the text-embedding pipeline: readdiff --git a/docs/src/content/docs/programming_guide/function.mdx b/docs/src/content/docs/programming_guide/function.mdxindex 9d28e030..89fb6d2a 100644--- a/docs/src/content/docs/programming_guide/function.mdx+++ b/docs/src/content/docs/programming_guide/function.mdx@@ -4,6 +4,11 @@ description: >The @coco.fn decorator makes Python functions participate in CocoIndex's changedetection, memoization, and execution pipeline β with async adapters, batching,and GPU-aware runners included.+rust_title: "Declaring *functions* with #[cocoindex::function]"+rust_description: >+ The #[cocoindex::function] attribute makes Rust functions participate in+ CocoIndex's change detection, memoization, and execution pipeline β with+ batching and GPU-aware runners included.---import LangTabs from '../../../components/LangTabs.astro';@@ -11,7 +16,7 @@ import LangTabs from '../../../components/LangTabs.astro';Read [Core Concepts](./core_concepts) for change detection and function memoization, with diagrams.:::-It's common to factor work into helper functions (for parsing, chunking, embedding, formatting, etc.). In CocoIndex, you can decorate any Python function with `@coco.fn` when you want to add incremental capabilities to it. The decorated function is still a normal Python function: its signature stays the same, and you can call it normally.+It's common to factor work into helper functions (for parsing, chunking, embedding, formatting, etc.). In CocoIndex, you can mark any function with <Lang only="python">`@coco.fn`</Lang><Lang only="rust">`#[cocoindex::function]`</Lang> when you want to add incremental capabilities to it. The marked function is still a normal function: its signature stays the same, and you can call it normally.<LangTabs><Fragment slot="python">@@ -41,12 +46,28 @@ let text = process_file(&ctx, file).await?;</Fragment></LangTabs>+<Lang only="python">+`@coco.fn` preserves the sync/async nature of the underlying function. Decorating a sync function yields a sync function; decorating an async function yields an async function.+</Lang>++<RustNote>The Rust SDK has no sync/async adapter (`as_async`, `as_sync`): a `#[cocoindex::function]` body is an `async fn` and runs on the Tokio runtime. Rust has no ambient component context: every function takes the component's `&Ctx` as its first argument, and the macro substitutes a scoped `Ctx` for the call.+</RustNote>++<Lang only="python">## How to think about `@coco.fn`+</Lang>++<Lang only="rust">++## How to think about `#[cocoindex::function]`++</Lang>+Decorating a function tells CocoIndex that calls to it are part of the incremental update engine. You still write normal Python, but CocoIndex can now:- Detect when inputs or code have changed (change detection)diff --git a/docs/src/data/docs-sidebar.ts b/docs/src/data/docs-sidebar.tsindex 9134a1a4..72d23c77 100644--- a/docs/src/data/docs-sidebar.ts+++ b/docs/src/data/docs-sidebar.ts@@ -1,7 +1,11 @@// V1 docs sidebar β mirrors ../docs/sidebars.ts from the Docusaurus source// on the v1 branch. Hand-maintained; update alongside `npm run port` when// the upstream tree changes. `slug` values must match Astro's URL shape-// for each file under src/content/docs/ (no extension; `/index` stripped).+// for each file under src/content/docs/ (no extension; `/index` stripped), or+// its frontmatter `route`. The tree is shared by both languages; each+// language's sidebar keeps only the pages in its tree (src/lib/lang.ts+// sidebarFor), so a slot such as getting_started/quickstart shows the Python+// page in /docs/ and the Rust page in /docs/rust/.export interface SidebarDoc {type: 'doc';@@ -27,7 +31,6 @@ export const sidebar: SidebarItem[] = [{ type: 'doc', slug: 'getting_started/overview', label: 'Overview' },{ type: 'doc', slug: 'getting_started/installation', label: 'Installation' },{ type: 'doc', slug: 'getting_started/quickstart', label: 'Quickstart' },- { type: 'doc', slug: 'getting_started/rust_quickstart', label: 'Rust SDK quickstart' },{ type: 'doc', slug: 'getting_started/ai_coding_agents', label: 'Use with AI coding agents' },],},@@ -115,7 +118,6 @@ export const sidebar: SidebarItem[] = [],},{ type: 'doc', slug: 'cli', label: 'CLI Reference' },- { type: 'doc', slug: 'cli_rust', label: 'CLI for Rust projects' },{ type: 'doc', slug: 'faq', label: 'FAQ' },{type: 'category',diff --git a/docs/src/data/redirects.ts b/docs/src/data/redirects.tsindex a50ef454..0b389d2a 100644--- a/docs/src/data/redirects.ts+++ b/docs/src/data/redirects.ts@@ -86,4 +86,11 @@ export const redirects: Record<string, string> = {'/examples/simple_vector_index': '/docs/examples/text-embedding/','/examples/google_drive': '/docs/examples/google-drive-embedding/','/examples/s3_sqs_pipeline': '/docs/examples/amazon-s3-embedding/',++ // The Rust tree (/docs/rust/, see src/lib/lang.ts). Its home is the Rust+ // overview until it has a landing page of its own; the two pages that were+ // Rust-only before the split moved to their Rust slots.+ '/rust': '/docs/rust/getting_started/overview/',+ '/getting_started/rust_quickstart': '/docs/rust/getting_started/quickstart/',+ '/cli_rust': '/docs/rust/cli/',};diff --git a/docs/src/layouts/DocsLayout.astro b/docs/src/layouts/DocsLayout.astroindex d922facc..a03ecb83 100644--- a/docs/src/layouts/DocsLayout.astro+++ b/docs/src/layouts/DocsLayout.astro@@ -9,7 +9,7 @@ import MermaidRenderer from '../components/MermaidRenderer.astro';import Analytics from '../components/Analytics.astro';import ScarfPixel from '../components/ScarfPixel.astro';import Foot from '../components/Foot.astro';-import { THEME_COLOR, SITE_URL, titleMarkup, pageUrl, pageMarkdownUrl, SKILL_MD_URL, DOCS_EDIT_BASE, SCARF_PIXEL_ID, OG_IMAGE_DOCS, OG_IMAGE_WIDTH, OG_IMAGE_HEIGHT, OG_IMAGE_DOCS_ALT } from '../consts';+import { THEME_COLOR, SITE_URL, titleMarkup, SKILL_MD_URL, DOCS_EDIT_BASE, SCARF_PIXEL_ID, OG_IMAGE_DOCS, OG_IMAGE_WIDTH, OG_IMAGE_HEIGHT, OG_IMAGE_DOCS_ALT } from '../consts';import { skillReferenceNames } from '../lib/skill-files';import ICON_COPY from '../icons/copy.svg?raw';import ICON_EXT from '../icons/external.svg?raw';@@ -17,6 +17,7 @@ import ICON_CHATGPT from '../icons/chatgpt.svg?raw';import ICON_CLAUDE from '../icons/claude.svg?raw';import { flatten, sidebar, type SidebarItem } from '../data/docs-sidebar';import { docsVersion, reviewedDate } from '../data/review-meta';+import { DEFAULT_LANG, LANG_LABEL, langHref, langMarkdownHref, langPageUrl, pageRegistry, sidebarFor, type Lang } from '../lib/lang';export interface IntroMeta {time?: string;@@ -36,6 +37,11 @@ export interface Props {sourcePath?: string;/** Per-page intro-meta strip (Time / Language / Requires) from frontmatter. */introMeta?: IntroMeta;+ /** SDK language of the page: Python at /docs/<slug>/, Rust at /docs/rust/<slug>/. */+ lang?: Lang;+ /** The page reads the same in both languages: the Rust copy's canonical is+ * the Python URL (frontmatter `neutral: true`). */+ neutral?: boolean;}const {@@ -46,7 +52,11 @@ const {headings,sourcePath,introMeta,+ lang = DEFAULT_LANG,+ neutral = false,} = Astro.props;+const reg = await pageRegistry();+const langSidebar = sidebarFor(sidebar, lang, reg);const base = import.meta.env.BASE_URL.replace(/\/$/, '');const renderedTitle = titleMarkup(titleMarkupRaw ?? title);@@ -66,16 +76,19 @@ const introItems = [{ k: 'Version', v: version, reviewed: false },{ k: 'Last reviewed', v: lastReviewed, reviewed: true },].filter((m) => m.v);-const canonical = pageUrl(slug);-const docsHome = new URL(`${base}/`, SITE_URL).toString();+// This page's own URL; a language-neutral Rust copy points search engines at+// the Python URL instead.+const ownUrl = langPageUrl(lang, slug);+const canonical = lang !== DEFAULT_LANG && neutral ? langPageUrl(DEFAULT_LANG, slug) : ownUrl;+const docsHome = langPageUrl(lang, '');const ogImage = OG_IMAGE_DOCS;// Contextual menu ("use this page with AI"): the raw-Markdown twin plus// one-click deep links that open ChatGPT/Claude with this page preloaded as// context. We pass the .md URL (not the inlined body) so it stays token-light// and always current. Mirrors Mintlify's contextual menu.-const mdHref = `${base}/${slug}.md`;-const mdAbs = pageMarkdownUrl(slug);+const mdHref = langMarkdownHref(lang, slug);+const mdAbs = new URL(mdHref, SITE_URL).toString();const aiPrompt =`Read ${mdAbs} β it is the raw Markdown for the CocoIndex (v1) docs page ` +`"${title}". Use it as context for my questions. Note: CocoIndex v1 is a ` +@@ -98,7 +111,7 @@ function findPath(items: SidebarItem[], acc: Array<{ label: string; href?: strinreturn [...acc, { label: item.label ?? slug }];}if (item.type === 'category') {- const next = [...acc, { label: item.label, href: item.slug ? `${base}/${item.slug}/` : undefined }];+ const next = [...acc, { label: item.label, href: item.slug ? langHref(lang, item.slug) : undefined }];if (item.slug === slug) return next;const down = findPath(item.items, next);if (down) return down;@@ -106,10 +119,10 @@ function findPath(items: SidebarItem[], acc: Array<{ label: string; href?: strin}return null;}-const crumbs = findPath(sidebar) ?? [{ label: title }];+const crumbs = findPath(langSidebar) ?? [{ label: title }];// Prev/next pager β drawn from the flat sidebar order.-const flat = flatten();+const flat = flatten(langSidebar);const i = flat.findIndex((e) => e.slug === slug);const prev = i > 0 ? flat[i - 1] : null;const next = i >= 0 && i < flat.length - 1 ? flat[i + 1] : null;@@ -136,14 +149,14 @@ const breadcrumbLd = {'@type': 'ListItem',position: idx + 2,name: c.label,- item: c.href ? new URL(c.href, SITE_URL).toString() : canonical,+ item: c.href ? new URL(c.href, SITE_URL).toString() : ownUrl,})),],};---<!doctype html>-<html lang="en">+<html lang="en" data-docs-lang={lang}><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />@@ -163,7 +176,7 @@ const breadcrumbLd = {<meta property="og:site_name" content="CocoIndex Docs" /><meta property="og:title" content={fullTitle} />{description && <meta property="og:description" content={description} />}- <meta property="og:url" content={canonical} />+ <meta property="og:url" content={ownUrl} /><meta property="og:image" content={ogImage} /><meta property="og:image:width" content={OG_IMAGE_WIDTH} /><meta property="og:image:height" content={OG_IMAGE_HEIGHT} />@@ -184,16 +197,16 @@ const breadcrumbLd = {<body><a class="skip-link" href="#main-content">Skip to content</a><Topbar mobileSheetId="mobileSheet" />- <MobileSheet currentSlug={slug} headings={headings} />+ <MobileSheet currentSlug={slug} headings={headings} lang={lang} sidebarItems={langSidebar} /><MermaidRenderer /><div class="layout">- <Sidebar currentSlug={slug} />+ <Sidebar currentSlug={slug} lang={lang} /><main class="content" id="main-content" tabindex="-1"><div class="page-head"><nav class="breadcrumb" aria-label="Breadcrumb">- <a href={`${base}/`}>Docs</a>+ <a href={langHref(lang, '')}>Docs</a>{crumbs.map((c, idx) => (<><span class="sep" aria-hidden="true">/</span>@@ -206,6 +219,7 @@ const breadcrumbLd = {)}</>))}+ <span class={`sdk-badge ${lang}`}>{LANG_LABEL[lang]} SDK</span></nav><div class="ai-actions">@@ -312,13 +326,13 @@ const breadcrumbLd = {{(prev || next) && (<div class="pager">{prev ? (- <a href={`${base}/${prev.slug}/`}>+ <a href={langHref(lang, prev.slug)}><span class="dir">Previous</span><span class="ttl">{prev.label ?? prev.slug}</span></a>) : <span />}{next ? (- <a class="next" href={`${base}/${next.slug}/`}>+ <a class="next" href={langHref(lang, next.slug)}><span class="dir">Next</span><span class="ttl">{next.label ?? next.slug}</span></a>diff --git a/docs/src/lib/lang.ts b/docs/src/lib/lang.tsnew file mode 100644index 00000000..8fce19a1--- /dev/null+++ b/docs/src/lib/lang.ts@@ -0,0 +1,254 @@+// SDK language of a docs page: the site has a Python tree at /docs/<slug>/ and+// a Rust tree at /docs/rust/<slug>/, rendered from one content collection.+// See docs/CONTENT_LANGUAGES.md for the authoring contract.+//+// Frontmatter keys read here:+// languages: [python, rust] trees the page appears in (default: both)+// route: <slug> the page's slug inside its trees, when it+// differs from its file path (a Rust-only page+// that takes the slot of a Python page, e.g.+// getting_started/rust_quickstart β route+// getting_started/quickstart)+// python_counterpart / rust_counterpart: <slug>+// where the language switch goes from this page+// when the page has no copy in that language+// neutral: true the page reads the same in both languages; the+// Rust copy's canonical URL is the Python one+import type { CollectionEntry } from 'astro:content';+import { getCollection } from 'astro:content';+import { DOCS_BASE, SITE_URL, docSlug } from '../consts';+import type { SidebarItem } from '../data/docs-sidebar';++export type Lang = 'python' | 'rust';+export const LANGS: readonly Lang[] = ['python', 'rust'];+export const DEFAULT_LANG: Lang = 'python';+export const LANG_LABEL: Record<Lang, string> = { python: 'Python', rust: 'Rust' };++/** Path prefix of a language's tree, after the docs base: '' or 'rust/'. */+export const langPrefix = (lang: Lang): string => (lang === DEFAULT_LANG ? '' : `${lang}/`);++/** Site-relative URL of a page (`slug` '' is the tree's root). */+export const langHref = (lang: Lang, slug: string): string =>+ `${DOCS_BASE}/${langPrefix(lang)}${slug ? `${slug}/` : ''}`;++/** Absolute URL of a page. */+export const langPageUrl = (lang: Lang, slug: string): string =>+ new URL(langHref(lang, slug), SITE_URL).toString();++/** Site-relative URL of a page's raw-Markdown twin. */+export const langMarkdownHref = (lang: Lang, slug: string): string =>+ `${DOCS_BASE}/${langPrefix(lang)}${slug}.md`;++type Doc = CollectionEntry<'docs'>;++export interface PageEntry {+ doc: Doc;+ /** Slug from the file path: what source links and old URLs use. */+ fileSlug: string;+ /** Slug inside the page's trees. */+ route: string;+ languages: Lang[];+ neutral: boolean;+ counterpart: Partial<Record<Lang, string>>;+}++const isLang = (v: unknown): v is Lang => v === 'python' || v === 'rust';++export function pageEntry(doc: Doc): PageEntry {+ const data = doc.data as Record<string, unknown>;+ const fileSlug = docSlug(doc.id);+ const listed = Array.isArray(data.languages) ? data.languages.filter(isLang) : [];+ const counterpart: Partial<Record<Lang, string>> = {};+ for (const lang of LANGS) {+ const c = data[`${lang}_counterpart`];+ if (typeof c === 'string' && c) counterpart[lang] = c.replace(/^\/+|\/+$/g, '');+ }+ return {+ doc,+ fileSlug,+ route: typeof data.route === 'string' && data.route ? data.route.replace(/^\/+|\/+$/g, '') : fileSlug,+ languages: listed.length ? listed : [...LANGS],+ neutral: data.neutral === true,+ counterpart,+ };+}++export interface PageRegistry {+ /** The page at `route` in a language's tree. */+ at(lang: Lang, route: string): PageEntry | undefined;+ /** The page whose file slug is `fileSlug`. */+ byFile(fileSlug: string): PageEntry | undefined;+ /** URL of the page a source link names (by file slug), in `lang`'s tree+ * when the page is there, else in the page's own language. */+ resolve(target: string, lang: Lang): { href: string; lang: Lang; route: string } | undefined;+ /** Where the language switch goes from `route` in `from` to `to`. */+ switchTarget(from: Lang, route: string, to: Lang): string;+ entries: PageEntry[];+}++let registry: Promise<PageRegistry> | undefined;++export function pageRegistry(): Promise<PageRegistry> {+ registry ??= build();+ return registry;+}++async function build(): Promise<PageRegistry> {+ const entries = (await getCollection('docs')).map(pageEntry);+ const trees: Record<Lang, Map<string, PageEntry>> = { python: new Map(), rust: new Map() };+ const files = new Map<string, PageEntry>();+ for (const e of entries) {+ files.set(e.fileSlug, e);+ for (const lang of e.languages) {+ const taken = trees[lang].get(e.route);+ if (taken) {+ throw new Error(+ `docs: two pages take route "${e.route}" in the ${lang} tree: ` ++ `${taken.fileSlug} and ${e.fileSlug} (set \`languages\` or \`route\`)`,+ );+ }+ trees[lang].set(e.route, e);+ }+ }++ const at = (lang: Lang, route: string) => trees[lang].get(route);++ // A page in `lang`'s tree that stands for `e`, which may live elsewhere.+ const standIn = (e: PageEntry, lang: Lang): string | undefined => {+ if (e.languages.includes(lang)) return e.route;+ const c = e.counterpart[lang];+ if (c && at(lang, c)) return c;+ if (at(lang, e.route)) return e.route; // another file takes the slot+ return undefined;+ };++ // A link names a file: it opens that file's page in the reader's language+ // when the page has one, else in the language it has.+ const resolve: PageRegistry['resolve'] = (target, lang) => {+ const t = target.replace(/^\/+|\/+$/g, '');+ const e = files.get(t);+ if (!e) return undefined;+ const l = e.languages.includes(lang) ? lang : e.languages[0];+ return { href: langHref(l, e.route), lang: l, route: e.route };+ };++ const switchTarget: PageRegistry['switchTarget'] = (from, route, to) => {+ const e = at(from, route);+ if (e) {+ const there = standIn(e, to);+ if (there !== undefined) return langHref(to, there);+ }+ // Section index, else the tree's root.+ const parts = route.split('/');+ for (let n = parts.length - 1; n > 0; n--) {+ const up = parts.slice(0, n).join('/');+ if (at(to, up)) return langHref(to, up);+ }+ return langHref(to, '');+ };++ return { at, byFile: (s) => files.get(s), resolve, switchTarget, entries };+}++/** The language of the page being rendered (set by the page route). */+export function currentLang(astro: { locals: unknown }): Lang {+ const v = (astro.locals as { lang?: unknown } | undefined)?.lang;+ return isLang(v) ? v : DEFAULT_LANG;+}++// ---------------------------------------------------------------------------+// Source-level language filtering, shared by the heading filter (TOC) and the+// raw-Markdown twins. Works on the MDX source: `<Lang only="x">β¦</Lang>` and+// LangTabs' `<Fragment slot="x">β¦</Fragment>` regions of the other language+// are removed. Fenced code must already be protected by the caller when the+// regions can contain fences with literal tags (raw-markdown does this); for+// heading extraction the plain regexes are enough.+// ---------------------------------------------------------------------------++const otherLang = (lang: Lang): Lang => (lang === 'python' ? 'rust' : 'python');++export function stripOtherLanguage(source: string, lang: Lang): string {+ const other = otherLang(lang);+ let s = source;+ // Language-only regions. `Lang` does not nest, so a lazy match is exact.+ s = s.replace(+ new RegExp(`<Lang\\s+only=["']${other}["'][^>]*>[\\s\\S]*?</Lang>`, 'g'),+ '',+ );+ // The other language's tab of a LangTabs pair.+ s = s.replace(+ new RegExp(`<Fragment\\s+slot=["']${other}["']\\s*>[\\s\\S]*?</Fragment>`, 'g'),+ '',+ );+ // Rust-only callouts.+ if (lang !== 'rust') s = s.replace(/<RustNote\b[^>]*>[\s\S]*?<\/RustNote>/g, '');+ if (lang !== 'python') s = s.replace(/<PythonNote\b[^>]*>[\s\S]*?<\/PythonNote>/g, '');+ return s;+}++/** Headings of the page as one language sees it (drops the other's). */+export function headingsFor<H extends { depth: number; text: string }>(+ headings: H[],+ source: string,+ lang: Lang,+): H[] {+ const kept = stripOtherLanguage(source, lang);+ const removed = source.length !== kept.length;+ if (!removed) return headings;+ // A heading is kept when its line survives the filter. Compare on the+ // heading text as Markdown writes it (`## Text`); headings rendered by+ // components keep their place since they are not in the source.+ const lines = (s: string) =>+ s+ .split('\n')+ .map((l) => /^\s*(#{1,6})\s+(.+?)\s*#*\s*$/.exec(l))+ .filter((m): m is RegExpExecArray => !!m)+ .map((m) => `${m[1].length}\u0000${plain(m[2])}`);+ const before = lines(source);+ const after = new Map<string, number>();+ for (const k of lines(kept)) after.set(k, (after.get(k) ?? 0) + 1);+ const dropped = new Map<string, number>();+ for (const k of before) {+ const n = after.get(k) ?? 0;+ if (n > 0) after.set(k, n - 1);+ else dropped.set(k, (dropped.get(k) ?? 0) + 1);+ }+ if (!dropped.size) return headings;+ return headings.filter((h) => {+ const k = `${h.depth}\u0000${plain(h.text)}`;+ const n = dropped.get(k) ?? 0;+ if (n > 0) {+ dropped.set(k, n - 1);+ return false;+ }+ return true;+ });+}++// Heading text as Astro reports it: no Markdown emphasis or code ticks.+const plain = (s: string) =>+ s+ .replace(/`([^`]*)`/g, '$1')+ .replace(/\*\*([^*]+)\*\*|\*([^*]+)\*|__([^_]+)__|_([^_]+)_/g, '$1$2$3$4')+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')+ .replace(/\s+/g, ' ')+ .trim();++// ---------------------------------------------------------------------------+// Sidebar per language: the shared tree (src/data/docs-sidebar.ts, written in+// routes) keeps only the pages that exist in the language's tree; a category+// with no page left is dropped.+// ---------------------------------------------------------------------------+export function sidebarFor(items: SidebarItem[], lang: Lang, reg: PageRegistry): SidebarItem[] {+ const out: SidebarItem[] = [];+ for (const item of items) {+ if (item.type === 'doc') {+ if (reg.at(lang, item.slug)) out.push(item);+ continue;+ }+ const children = sidebarFor(item.items, lang, reg);+ const slug = item.slug && reg.at(lang, item.slug) ? item.slug : undefined;+ if (children.length || slug) out.push({ ...item, slug, items: children });+ }+ return out;+}diff --git a/docs/src/lib/llms.ts b/docs/src/lib/llms.tsnew file mode 100644index 00000000..bb8c05a5--- /dev/null+++ b/docs/src/lib/llms.ts@@ -0,0 +1,166 @@+// Builds /docs/llms.txt (Python) and /docs/rust/llms.txt (Rust) β a+// machine-readable index of one SDK language's docs for LLMs and agents (see+// https://llmstxt.org/). Built from the same sidebar tree and per-page+// descriptions that drive the site, so it stays in sync automatically.+import { DOCS_BASE, GITHUB_REPO, SITE_URL, SKILL_MD_URL, docTitle } from '../consts';+import { flatten, sidebar, type SidebarDoc } from '../data/docs-sidebar';+import { getCollection } from 'astro:content';+import { mdxToMarkdown, docSrcDir } from './raw-markdown';+import { EXAMPLE_CATALOG, EXAMPLE_CATALOG_GROUPS, examples, findExample } from '../data/examples';+import { langMarkdownHref, langPageUrl, langPrefix, pageRegistry, sidebarFor, type Lang } from './lang';++const oneLine = (s?: string) => (s ?? '').replace(/\s+/g, ' ').trim();++export async function llmsTxt(lang: Lang): Promise<string> {+ const reg = await pageRegistry();+ const tree = sidebarFor(sidebar, lang, reg);+ const url = (slug: string) => langPageUrl(lang, slug);+ const markdownUrl = (slug: string) => new URL(langMarkdownHref(lang, slug), SITE_URL).toString();+ const LLMS_FULL_TXT_URL = new URL(`${DOCS_BASE}/${langPrefix(lang)}llms-full.txt`, SITE_URL).toString();+ const desc = (slug: string) => {+ const e = reg.at(lang, slug);+ if (!e) return '';+ const data = e.doc.data as Record<string, unknown>;+ const d = lang === 'rust' && typeof data.rust_description === 'string' ? data.rust_description : e.doc.data.description;+ return oneLine(d);+ };+ const sidebarRoot = tree;++ const line = (slug: string, label?: string) => {+ const d = desc(slug);+ return `- [${label ?? slug}](${url(slug)})${d ? `: ${d}` : ''}`;+ };++ const out: string[] = [+ lang === 'rust' ? '# CocoIndex Docs β Rust SDK' : '# CocoIndex Docs',+ '',+ '> CocoIndex is an ultra-performant framework for building data pipelines for AI, ' ++ 'with built-in incremental processing. Declare what your target should look like ' ++ 'as a function of your source β the Rust engine keeps it in sync, reprocessing ' ++ 'only what changed.',+ '',+ lang === 'rust'+ ? `> This index lists the Rust SDK pages (/docs/rust/). The Python SDK pages are indexed at ${new URL(`${DOCS_BASE}/llms.txt`, SITE_URL)}.`+ : `> This index lists the Python SDK pages. The Rust SDK pages are indexed at ${new URL(`${DOCS_BASE}/rust/llms.txt`, SITE_URL)}.`,+ '',+ '> Full docs text in one file: ' + LLMS_FULL_TXT_URL ++ `. Docs pages and example walkthroughs have raw Markdown twins by replacing the trailing slash with \`.md\`, e.g. ${markdownUrl('programming_guide/core_concepts')} β and they are all included in llms-full.txt.`,+ '',+ '> Coding agents: install the CocoIndex skill before writing v1 code β ' ++ SKILL_MD_URL ++ ' (teaches the correct v1 API; without it, LLMs tend to hallucinate the deprecated v0 flow-builder DSL).',+ '',+ ];++ // Standalone top-level docs (Core Concepts, CLI, FAQ) surfaced first.+ const standalone = sidebarRoot.filter((i): i is SidebarDoc => i.type === 'doc');+ if (standalone.length) {+ out.push('## Key pages');+ for (const d of standalone) out.push(line(d.slug, d.label));+ out.push('');+ }++ for (const item of sidebarRoot) {+ if (item.type !== 'category') continue;+ out.push(`## ${item.label}`);+ if (item.slug) out.push(line(item.slug, item.label));+ for (const sub of item.items) {+ if (sub.type === 'doc') out.push(line(sub.slug, sub.label));+ else for (const s2 of sub.items) if (s2.type === 'doc') out.push(line(s2.slug, s2.label));+ }+ out.push('');+ }++ if (lang === 'rust') {+ out.push('## Examples');+ out.push(`> Runnable Rust SDK examples: ${GITHUB_REPO}/tree/main/examples/rust β each is a standalone Cargo workspace; run it with \`cargo run\` or the Rust CLI (\`cocoindex update\`).`);+ out.push('');+ return out.join('\n');+ }++ // Every runnable example in the monorepo β the on-page listing curates a few,+ // but agents should see the whole set (and how to clone any one) in one fetch.+ // Documented examples link to their walkthrough; the rest link to source.+ out.push('## Examples');+ out.push(+ `> ${EXAMPLE_CATALOG.length} runnable examples in the monorepo. ` ++ 'Clone the repo with `git clone ' ++ GITHUB_REPO ++ '`, then `cd cocoindex/examples/<dir>`, copy `.env.example` if present, install with `pip install -e .`, and run the command shown for that example.',+ );+ out.push('');+ for (const group of EXAMPLE_CATALOG_GROUPS) {+ out.push(`### ${group.title}`);+ out.push(`> ${group.blurb}`);+ out.push('');+ for (const ex of group.entries) {+ const href = ex.docs+ ? url(`examples/${ex.docs}`)+ : `${GITHUB_REPO}/tree/main/examples/${ex.dir}`;+ out.push(`- [${ex.title}](${href}): ${oneLine(ex.description)} (examples/${ex.dir}; run: \`${ex.run ?? 'cocoindex update main'}\`)`);+ }+ out.push('');+ }++ return out.join('\n');+}++// Builds /docs/llms-full.txt (Python) and /docs/rust/llms-full.txt (Rust):+// the full text of one SDK language's docs pages (and, for Python, the example+// walkthroughs) in one file, for LLMs and agents that want everything in a+// single fetch. The llms.txt of the same language is the lighter index.++// Include-fragments are embedded verbatim in their host page (cli.mdx inlines+// cli_commands.mdx), so emitting them standalone would duplicate the content.+const INCLUDE_FRAGMENTS = new Set(['cli_commands']);++export async function llmsFullTxt(lang: Lang): Promise<string> {+ const reg = await pageRegistry();+ const indexUrl = new URL(`${DOCS_BASE}/${langPrefix(lang)}llms.txt`, SITE_URL).toString();+ const out: string[] = [+ lang === 'rust' ? '# CocoIndex Docs β Rust SDK, full text' : '# CocoIndex Docs β full text',+ '',+ (lang === 'rust'+ ? '> The complete CocoIndex Rust SDK documentation concatenated into one file for LLMs and agents. '+ : '> The complete CocoIndex documentation and example walkthroughs concatenated ' ++ 'into one file for LLMs and agents. ') ++ 'Each section below is one docs page' + (lang === 'rust' ? '' : ' or example page') + ', in reading order. ' ++ `For a lighter index of pages${lang === 'rust' ? '' : ' and examples'}, see ${indexUrl}.`,+ ];++ const seen = new Set<string>();+ const emit = (route: string) => {+ const e = reg.at(lang, route);+ if (!e || seen.has(route) || INCLUDE_FRAGMENTS.has(e.fileSlug)) return;+ seen.add(route);+ const data = e.doc.data as Record<string, unknown>;+ const raw = lang === 'rust' && typeof data.rust_title === 'string' ? data.rust_title : e.doc.data.title;+ const title = docTitle(e.doc.id, raw);+ out.push('', '---', '', `# ${title}`, '', `Source: ${langPageUrl(lang, route)}`, '', mdxToMarkdown(e.doc.body ?? '', docSrcDir(e.doc), lang));+ };++ // Sidebar order first, then any stray pages of the language not in the tree.+ for (const e of flatten(sidebarFor(sidebar, lang, reg))) emit(e.slug);+ for (const e of reg.entries) if (e.languages.includes(lang)) emit(e.route);++ if (lang === 'rust') return out.join('\n') + '\n';++ const exampleUrl = (slug: string) => langPageUrl('python', `examples/${slug}`);+ const examplePosts = await getCollection('examplePosts');+ const byExampleSlug = new Map(examplePosts.map((e) => [e.id.replace(/\.mdx?$/, ''), e]));+ const emittedExamples = new Set<string>();+ const emitExample = (slug: string) => {+ const post = byExampleSlug.get(slug);+ if (!post || emittedExamples.has(slug)) return;+ emittedExamples.add(slug);+ const meta = findExample(slug);+ const title = docTitle(slug, meta?.title);+ out.push('', '---', '', `# Example: ${title}`, '', `Source: ${exampleUrl(slug)}`, '', mdxToMarkdown(post.body ?? '', 'examples'));+ };++ out.push('', '---', '', '# Example Walkthroughs');+ for (const e of examples) emitExample(e.slug);+ for (const slug of byExampleSlug.keys()) emitExample(slug);++ return out.join('\n') + '\n';+}diff --git a/docs/src/lib/raw-markdown.ts b/docs/src/lib/raw-markdown.tsindex ecdeaa93..194bccef 100644--- a/docs/src/lib/raw-markdown.ts+++ b/docs/src/lib/raw-markdown.ts@@ -24,6 +24,7 @@ import type { CollectionEntry } from 'astro:content';import { getCollection, getEntry } from 'astro:content';import { DOCS_BASE, GITHUB_REPO, docSlug, docTitle, pageUrl, LLMS_TXT_URL, SKILL_MD_URL } from '../consts';import { findExample } from '../data/examples';+import { type Lang, DEFAULT_LANG, langPrefix, pageRegistry, stripOtherLanguage } from './lang';import { FENCE, INLINE_CODE, MDX_COMMENT } from './fence.mjs';const SENT = '\x00'; // sentinel: cannot occur in source text@@ -61,8 +62,8 @@ const memo = import.meta.env.DEV ? null : new Map<string, string>();// resolved against it and emitted as root-relative page URLs (/docs/<slug>/),// the form remark-link-checker gives the HTML pages; the .md twins serve the// body verbatim, and index pages sit one level shallower than their source.-export function mdxToMarkdown(body: string, srcDir = ''): string {- const key = `${srcDir}\u0000${body ?? ''}`;+export function mdxToMarkdown(body: string, srcDir = '', lang?: Lang): string {+ const key = `${lang ?? ''}\u0000${srcDir}\u0000${body ?? ''}`;const cached = memo?.get(key);if (cached !== undefined) return cached;@@ -74,6 +75,10 @@ export function mdxToMarkdown(body: string, srcDir = ''): string {const inlines: string[] = [];s = protect(s, INLINE_CODE, inlines, 'C');+ // 1b. Keep only this language's content (code is behind sentinels, so a+ // literal `<Lang>` inside a code sample is safe).+ if (lang) s = stripOtherLanguage(s, lang);+// 2. Strip ESM import lines (require `from` so we never eat prose starting// with the word "import"), MDX `export β¦` scaffolding, and MDX comments.s = s.replace(/^[ \t]*import\b.+\bfrom\b.+$/gm, '');@@ -124,9 +129,16 @@ export function mdxToMarkdown(body: string, srcDir = ''): string {// Single source for the docs-page route map, shared by the HTML route// ([...slug].astro) and the Markdown twin ([...slug].md.ts) so the two can// never enumerate different page sets.+// One path per (page, language): `/docs/<route>/` for Python and+// `/docs/rust/<route>/` for Rust, for each language the page lists.export async function docStaticPaths() {- const docs = await getCollection('docs');- return docs.map((doc) => ({ params: { slug: docSlug(doc.id) }, props: { doc } }));+ const { entries } = await pageRegistry();+ return entries.flatMap((entry) =>+ entry.languages.map((lang) => ({+ params: { slug: `${langPrefix(lang)}${entry.route}` },+ props: { doc: entry.doc, lang, route: entry.route },+ })),+ );}// Shared top-of-page banner for every agent-facing .md twin: v1 guard, then@@ -155,15 +167,21 @@ export function docSrcDir(doc: CollectionEntry<'docs'>): string {return dir === '.' ? '' : dir;}-export function buildDocMarkdown(doc: CollectionEntry<'docs'>): string {- const slug = docSlug(doc.id);- const title = docTitle(doc.id, doc.data.title);+export function buildDocMarkdown(+ doc: CollectionEntry<'docs'>,+ lang: Lang = DEFAULT_LANG,+ route: string = docSlug(doc.id),+): string {+ const data = doc.data as Record<string, unknown>;+ const rustTitle = lang === 'rust' && typeof data.rust_title === 'string' ? data.rust_title : undefined;+ const title = docTitle(doc.id, rustTitle ?? doc.data.title);+ const slug = `${langPrefix(lang)}${route}`;const guard = buildGuard(slug,`**CocoIndex v1.** This page documents CocoIndex **v1** β a ground-up redesign ` +`from v0. When writing code, ignore any v0 flow-builder DSL or deprecated decorators.`,);- return `# ${title}\n\n${guard}\n\n${mdxToMarkdown(doc.body, docSrcDir(doc))}\n`;+ return `# ${title}\n\n${guard}\n\n${mdxToMarkdown(doc.body, docSrcDir(doc), lang)}\n`;}// Full Markdown body for an example walkthrough's /examples/<slug>.md twin.diff --git a/docs/src/middleware.ts b/docs/src/middleware.tsindex d6ce9c58..a167da93 100644--- a/docs/src/middleware.ts+++ b/docs/src/middleware.ts@@ -1,6 +1,6 @@import { defineMiddleware } from 'astro:middleware';-import { getCollection } from 'astro:content';-import { docSlug, DOCS_BASE as base } from './consts';+import { DOCS_BASE as base } from './consts';+import { pageRegistry } from './lib/lang';import { buildDocMarkdown, buildExampleMarkdown } from './lib/raw-markdown';import { readSkillFile, skillReferenceNames } from './lib/skill-files';@@ -29,8 +29,10 @@ export const onRequest = defineMiddleware(async (context, next) => {const body = await buildExampleMarkdown(slug.slice('examples/'.length));if (body !== undefined) return markdown(body);}- const doc = (await getCollection('docs')).find((d) => docSlug(d.id) === slug);- if (doc) return markdown(buildDocMarkdown(doc));+ const lang = slug.startsWith('rust/') ? 'rust' : 'python';+ const route = lang === 'rust' ? slug.slice('rust/'.length) : slug;+ const entry = (await pageRegistry()).at(lang, route);+ if (entry) return markdown(buildDocMarkdown(entry.doc, lang, route));}return next();});diff --git a/docs/src/pages/[...slug].astro b/docs/src/pages/[...slug].astroindex 2d485c18..6d14f819 100644--- a/docs/src/pages/[...slug].astro+++ b/docs/src/pages/[...slug].astro@@ -1,40 +1,57 @@---import { render, type CollectionEntry } from 'astro:content';import DocsLayout from '../layouts/DocsLayout.astro';-import { docSlug, titleText } from '../consts';+import LangLink from '../components/LangLink.astro';+import Lang from '../components/Lang.astro';+import LangTabs from '../components/LangTabs.astro';+import RustNote from '../components/RustNote.astro';+import { titleText } from '../consts';import { docStaticPaths } from '../lib/raw-markdown';+import { headingsFor, pageEntry, type Lang } from '../lib/lang';export const getStaticPaths = docStaticPaths;-type Props = { doc: CollectionEntry<'docs'> };-const { doc } = Astro.props as Props;+type Props = { doc: CollectionEntry<'docs'>; lang: Lang; route: string };+const { doc, lang, route } = Astro.props as Props;+// Components inside the page body (Lang, LangTabs, RustNote, LangLink) read+// the page's language from here; see src/lib/lang.ts currentLang().+(Astro.locals as { lang?: Lang }).lang = lang;+const { Content, headings: mdHeadings } = await render(doc);+const headings = headingsFor(mdHeadings, doc.body ?? '', lang);-const slug = docSlug(doc.id);const rel = (doc as unknown as { filePath?: string }).filePath?.split('src/content/docs/').pop();const sourcePath = `src/content/docs/${rel ?? `${doc.id}.md`}`;// Title may contain *asterisks* marking coral accent segments-// (see src/consts.ts titleMarkup); plain metadata strips them.-const rawTitle: string =- typeof doc.data.title === 'string' && doc.data.title.length > 0 ? doc.data.title : slug;-const title = rawTitle;+// (see src/consts.ts titleMarkup); plain metadata strips them. A Rust page+// may override both with `rust_title` / `rust_description`.+const data = doc.data as Record<string, unknown>;+const pick = (key: 'title' | 'description'): string | undefined => {+ const own = lang === 'rust' ? data[`rust_${key}`] : undefined;+ const v = typeof own === 'string' && own.length > 0 ? own : data[key];+ return typeof v === 'string' && v.length > 0 ? v : undefined;+};+const rawTitle = pick('title') ?? route;const metaTitle = titleText(rawTitle);-const description =- typeof doc.data.description === 'string' ? doc.data.description : undefined;+const description = pick('description');const introMeta = doc.data.meta;+const { neutral } = pageEntry(doc);---<DocsLayouttitle={metaTitle}- titleMarkup={title}+ titleMarkup={rawTitle}description={description}- slug={slug}- headings={mdHeadings}+ slug={route}+ lang={lang}+ neutral={neutral}+ headings={headings}sourcePath={sourcePath}introMeta={introMeta}>- <Content />+ {/* Lang, LangTabs and RustNote need no import in a page. */}+ <Content components={{ a: LangLink, Lang, LangTabs, RustNote }} /></DocsLayout>diff --git a/docs/src/pages/[...slug].md.ts b/docs/src/pages/[...slug].md.tsindex 9be89eee..63c64684 100644--- a/docs/src/pages/[...slug].md.ts+++ b/docs/src/pages/[...slug].md.ts@@ -1,17 +1,19 @@// Emits a raw-Markdown twin of every content-collection docs page at-// /docs/<slug>.md β agents and LLMs prefer clean Markdown over scraping rendered-// HTML. Shares the slug map with [...slug].astro via docStaticPaths.-// The Markdown body is built by buildDocMarkdown (shared with the dev-only-// middleware that patches Astro's dev-server 404 on these endpoints).+// /docs/<slug>.md (Python) and /docs/rust/<slug>.md (Rust) β agents and LLMs+// prefer clean Markdown over scraping rendered HTML. Shares the path map with+// [...slug].astro via docStaticPaths, so the two never enumerate different+// page sets. The Markdown body is built by buildDocMarkdown (shared with the+// dev-only middleware that patches Astro's dev-server 404 on these endpoints).import type { APIRoute } from 'astro';import { type CollectionEntry } from 'astro:content';import { buildDocMarkdown, docStaticPaths } from '../lib/raw-markdown';+import type { Lang } from '../lib/lang';export const getStaticPaths = docStaticPaths;export const GET: APIRoute = ({ props }) => {- const { doc } = props as { doc: CollectionEntry<'docs'> };- return new Response(buildDocMarkdown(doc), {+ const { doc, lang, route } = props as { doc: CollectionEntry<'docs'>; lang: Lang; route: string };+ return new Response(buildDocMarkdown(doc, lang, route), {headers: { 'Content-Type': 'text/markdown; charset=utf-8' },});};diff --git a/docs/src/pages/index.astro b/docs/src/pages/index.astroindex 46d4b466..3b3b9568 100644--- a/docs/src/pages/index.astro+++ b/docs/src/pages/index.astro@@ -103,7 +103,7 @@ app.update_blocking()`;---<!doctype html>-<html lang="en">+<html lang="en" data-docs-lang="python"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />@@ -121,7 +121,7 @@ app.update_blocking()`;<MobileSheet sidebarItems={sidebar} /><div class="layout dh-layout">- <Sidebar currentSlug="" />+ <Sidebar currentSlug="" lang="python" /><main class="content dh-main" id="main-content" tabindex="-1"><section class="dh-hero" aria-labelledby="dh-title">diff --git a/docs/src/pages/llms-full.txt.ts b/docs/src/pages/llms-full.txt.tsindex 1df5541c..cdad0fbb 100644--- a/docs/src/pages/llms-full.txt.ts+++ b/docs/src/pages/llms-full.txt.ts@@ -1,63 +1,10 @@-// Generates /docs/llms-full.txt β the full text of every docs page and example-// walkthrough concatenated into one file, for LLMs and agents that want the-// programming guide + connector reference + runnable examples in a single fetch-// (see https://llmstxt.org/). /docs/llms.txt is the lighter index.+// /docs/llms-full.txt β the full text of the Python SDK docs and the example+// walkthroughs. Built by src/lib/llms.ts, which also builds the Rust one+// (/docs/rust/llms-full.txt).import type { APIRoute } from 'astro';-import { getCollection } from 'astro:content';-import { docSlug, docTitle, pageUrl } from '../consts';-import { examples, findExample } from '../data/examples';-import { flatten } from '../data/docs-sidebar';-import { mdxToMarkdown, docSrcDir } from '../lib/raw-markdown';+import { llmsFullTxt } from '../lib/llms';-const exampleUrl = (slug: string) => pageUrl(`examples/${slug}`);--// Include-fragments are embedded verbatim in their host page (cli.mdx inlines-// cli_commands.mdx), so emitting them standalone would duplicate the content.-const INCLUDE_FRAGMENTS = new Set(['cli_commands']);--export const GET: APIRoute = async () => {- const docs = await getCollection('docs');- const bySlug = new Map(docs.map((d) => [docSlug(d.id), d]));-- const out: string[] = [- '# CocoIndex Docs β full text',- '',- '> The complete CocoIndex documentation and example walkthroughs concatenated ' +- 'into one file for LLMs and agents. Each section below is one docs page or ' +- 'example page, in reading order. ' +- 'For a lighter index of pages and examples, see /docs/llms.txt.',- ];-- const seen = new Set<string>();- const emit = (slug: string) => {- const d = bySlug.get(slug);- if (!d || seen.has(slug)) return;- seen.add(slug);- const title = docTitle(d.id, d.data.title);- out.push('', '---', '', `# ${title}`, '', `Source: ${pageUrl(slug)}`, '', mdxToMarkdown(d.body, docSrcDir(d)));- };-- // Sidebar order first, then any stray docs not in the tree.- for (const e of flatten()) emit(e.slug);- for (const slug of bySlug.keys()) if (!INCLUDE_FRAGMENTS.has(slug)) emit(slug);-- const examplePosts = await getCollection('examplePosts');- const byExampleSlug = new Map(examplePosts.map((e) => [e.id.replace(/\.mdx?$/, ''), e]));- const emittedExamples = new Set<string>();- const emitExample = (slug: string) => {- const post = byExampleSlug.get(slug);- if (!post || emittedExamples.has(slug)) return;- emittedExamples.add(slug);- const meta = findExample(slug);- const title = docTitle(slug, meta?.title);- out.push('', '---', '', `# Example: ${title}`, '', `Source: ${exampleUrl(slug)}`, '', mdxToMarkdown(post.body, 'examples'));- };-- out.push('', '---', '', '# Example Walkthroughs');- for (const e of examples) emitExample(e.slug);- for (const slug of byExampleSlug.keys()) emitExample(slug);-- return new Response(out.join('\n') + '\n', {+export const GET: APIRoute = async () =>+ new Response(await llmsFullTxt('python'), {headers: { 'Content-Type': 'text/plain; charset=utf-8' },});-};diff --git a/docs/src/pages/llms.txt.ts b/docs/src/pages/llms.txt.tsindex fd7f7405..8bf657b3 100644--- a/docs/src/pages/llms.txt.ts+++ b/docs/src/pages/llms.txt.ts@@ -1,91 +1,9 @@-// Generates /docs/llms.txt β a machine-readable index of the docs for LLMs and-// agents (see https://llmstxt.org/). Built from the same sidebar tree and-// per-page descriptions that drive the site, so it stays in sync automatically.+// /docs/llms.txt β the Python SDK docs index. Built by src/lib/llms.ts, which+// also builds the Rust one (/docs/rust/llms.txt).import type { APIRoute } from 'astro';-import { getCollection } from 'astro:content';-import {- GITHUB_REPO,- docSlug,- pageUrl as url,- pageMarkdownUrl as markdownUrl,- LLMS_FULL_TXT_URL,- SKILL_MD_URL,-} from '../consts';-import { sidebar, type SidebarDoc } from '../data/docs-sidebar';-import { EXAMPLE_CATALOG, EXAMPLE_CATALOG_GROUPS } from '../data/examples';-const oneLine = (s?: string) => (s ?? '').replace(/\s+/g, ' ').trim();+import { llmsTxt } from '../lib/llms';-export const GET: APIRoute = async () => {- const docs = await getCollection('docs');- const desc = new Map<string, string>();- for (const d of docs) desc.set(docSlug(d.id), oneLine(d.data.description));-- const line = (slug: string, label?: string) => {- const d = desc.get(slug);- return `- [${label ?? slug}](${url(slug)})${d ? `: ${d}` : ''}`;- };-- const out: string[] = [- '# CocoIndex Docs',- '',- '> CocoIndex is an ultra-performant framework for building data pipelines for AI, ' +- 'with built-in incremental processing. Declare what your target should look like ' +- 'as a function of your source β the Rust engine keeps it in sync, reprocessing ' +- 'only what changed.',- '',- '> Full docs text in one file: ' + LLMS_FULL_TXT_URL +- `. Docs pages and example walkthroughs have raw Markdown twins by replacing the trailing slash with \`.md\`, e.g. ${markdownUrl('programming_guide/core_concepts')} β and they are all included in llms-full.txt.`,- '',- '> Coding agents: install the CocoIndex skill before writing v1 code β ' +- SKILL_MD_URL +- ' (teaches the correct v1 API; without it, LLMs tend to hallucinate the deprecated v0 flow-builder DSL).',- '',- ];-- // Standalone top-level docs (Core Concepts, CLI, FAQ) surfaced first.- const standalone = sidebar.filter((i): i is SidebarDoc => i.type === 'doc');- if (standalone.length) {- out.push('## Key pages');- for (const d of standalone) out.push(line(d.slug, d.label));- out.push('');- }-- for (const item of sidebar) {- if (item.type !== 'category') continue;- out.push(`## ${item.label}`);- if (item.slug) out.push(line(item.slug, item.label));- for (const sub of item.items) {- if (sub.type === 'doc') out.push(line(sub.slug, sub.label));- else for (const s2 of sub.items) if (s2.type === 'doc') out.push(line(s2.slug, s2.label));- }- out.push('');- }-- // Every runnable example in the monorepo β the on-page listing curates a few,- // but agents should see the whole set (and how to clone any one) in one fetch.- // Documented examples link to their walkthrough; the rest link to source.- out.push('## Examples');- out.push(- `> ${EXAMPLE_CATALOG.length} runnable examples in the monorepo. ` +- 'Clone the repo with `git clone ' +- GITHUB_REPO +- '`, then `cd cocoindex/examples/<dir>`, copy `.env.example` if present, install with `pip install -e .`, and run the command shown for that example.',- );- out.push('');- for (const group of EXAMPLE_CATALOG_GROUPS) {- out.push(`### ${group.title}`);- out.push(`> ${group.blurb}`);- out.push('');- for (const ex of group.entries) {- const href = ex.docs- ? url(`examples/${ex.docs}`)- : `${GITHUB_REPO}/tree/main/examples/${ex.dir}`;- out.push(`- [${ex.title}](${href}): ${oneLine(ex.description)} (examples/${ex.dir}; run: \`${ex.run ?? 'cocoindex update main'}\`)`);- }- out.push('');- }-- return new Response(out.join('\n'), {+export const GET: APIRoute = async () =>+ new Response(await llmsTxt('python'), {headers: { 'Content-Type': 'text/plain; charset=utf-8' },});-};diff --git a/docs/src/pages/rust/llms-full.txt.ts b/docs/src/pages/rust/llms-full.txt.tsnew file mode 100644index 00000000..ab9f6bd7--- /dev/null+++ b/docs/src/pages/rust/llms-full.txt.ts@@ -0,0 +1,9 @@+// /docs/rust/llms-full.txt β the full text of the Rust SDK docs. Built by+// src/lib/llms.ts.+import type { APIRoute } from 'astro';+import { llmsFullTxt } from '../../lib/llms';++export const GET: APIRoute = async () =>+ new Response(await llmsFullTxt('rust'), {+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },+ });diff --git a/docs/src/pages/rust/llms.txt.ts b/docs/src/pages/rust/llms.txt.tsnew file mode 100644index 00000000..164630cb--- /dev/null+++ b/docs/src/pages/rust/llms.txt.ts@@ -0,0 +1,8 @@+// /docs/rust/llms.txt β the Rust SDK docs index. Built by src/lib/llms.ts.+import type { APIRoute } from 'astro';+import { llmsTxt } from '../../lib/llms';++export const GET: APIRoute = async () =>+ new Response(await llmsTxt('rust'), {+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },+ });diff --git a/docs/src/styles/site.css b/docs/src/styles/site.cssindex 57f92535..76c31806 100644--- a/docs/src/styles/site.css+++ b/docs/src/styles/site.css@@ -791,3 +791,20 @@ a { color: var(--maroon-ink); }}:root .diagram-scroll-hint[hidden] { display: none; }}++/* SDK language (src/lib/lang.ts): the breadcrumb badge on every docs page,+ and the colours the language switch and the Rust callout use. */+:root { --lang-python: #4b8bbe; --lang-rust: #e8743d; }+.breadcrumb .sdk-badge {+ margin-left: 10px;+ padding: 1px 7px;+ font-family: var(--mono);+ font-size: 0.6875rem;+ line-height: 1.6;+ letter-spacing: 0.01em;+ border: 1px solid var(--rule-strong);+ border-radius: 5px;+ white-space: nowrap;+}+.breadcrumb .sdk-badge.python { color: var(--lang-python); }+.breadcrumb .sdk-badge.rust { color: var(--lang-rust); }